Thread: Is it possible to improve this program

  1. #1
    Registered User
    Join Date
    Apr 2018

    Lightbulb Is it possible to improve this program

    I need my teacher today to pass the program, I wrote it and here's her code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <errno.h>
    int sizeRepeats(char *s, int count) //Get repeat str result size
        if(count <= 1)
            return -1;
        return (int)strlen(s)*count;
    char * repeat(char *s, int count, char *dest)
        if(count <= 1)
            return "Error";
        for(int i=0; i<count; i++)
            strcat(dest, s);
        return dest;
    int main(int argc, char const *argv[])
        char *str = "Testing";
        char buf[sizeRepeats(str, 5)];
        printf("'%s'\n", repeat(str, 5, buf));
        return 0;
    Is this a normal release or can you do better and work even faster?

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    The edge of the known universe
    1. Your buffer is short by 1 byte.
    2. It isn't initialized to \0, so strcat is broken.
    3. Variable length arrays need a C99 compiler.

    You can make it quicker by making repeat calculate where each string starts.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    misoturbutc Hodor's Avatar
    Join Date
    Nov 2013
    char * repeat(char *s, int count, char *dest)
    Would better be
    char * repeat(const char *s, int count, char *dest)
    In addition to const qualifying 's', 'count' might be better as size_t. If you changed 'count' to size_t you may as well also get rid of the useless cast on line 9 and make that function return size_t as well. Line 23 should also be const qualified IMO since it would be undefined behaviour to modify what 'str' points to anyway.

    What size is the array if sizeRepeats() returns -1?

  4. #4
    Registered User
    Join Date
    Apr 2017
    I recommend you give a value to buf before the call to repeat().
    strcpy(buf, str);

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. How can I improve my C program?
    By cyberjupiter in forum C Programming
    Replies: 7
    Last Post: 09-09-2017, 05:47 AM
  2. How to improve this program
    By raj21 in forum C Programming
    Replies: 1
    Last Post: 11-09-2015, 02:27 PM
  3. How can I improve this program?
    By WHOLEGRAIN in forum C++ Programming
    Replies: 14
    Last Post: 03-06-2011, 02:53 AM
  4. help to improve program efficiency and speed
    By godhand in forum C Programming
    Replies: 11
    Last Post: 10-19-2003, 04:25 PM
  5. improve program.
    By emperor in forum C Programming
    Replies: 5
    Last Post: 01-05-2003, 01:34 AM

Tags for this Thread