Strcpy and strcat sometimes cause problems
Hi i have code like below
char *str ; strcpy(str, "\t<"); strcat(str, time); strcat(str, ">["); strcat(str, user); strcat(str, "]"); strcat(str, "("); strcat(str, baseName); strcat(str, ") $ "); printf("\String is now: %s\n", str); This code works, but when I use the Xcode parsing function, it says: βThe function call argument is an uninitialized valueβ and also sometimes causes my program to crash .. when I delete it, then it works fine ... What's wrong with by this? Thanks
strcpy and strcat are used to copy and concatenate strings into a dedicated char array.
Since str not initialized, you write somewhere in memory, and this is bad because you are corrupting other data. This may work at that moment, but sooner or later you will program a failure.
You must allocate memory when declaring str:
char str[100];
In addition, strcat inefficient, as it has to look for the end of a line to know where to concatenate characters. Using sprintf will be more efficient:
sprintf(str, "\t<%s>[%s](%s) $ ", time, user, baseName);
Finally, if you cannot guarantee that the generated string will match the array, you better use snsprintf.
You do not allocate memory, and you leave str uninitialized. All subsequent entries are made using an uninitialized pointer that indicates "somewhere" - this is undefined behavior.
You must allocate (and later free) memory sufficient to store the resulting string:
char *str = malloc( computeResultSizeSomehow() ); if( str == 0 ) { // malloc failed - handle as fatal error } //proceed with your code, then free( str ); This is much simpler and without buffer overflow errors:
#define BUFFERSIZE 512 char str[BUFFERSIZE]; snprintf(str, BUFFERSIZE, "\t<%s>[%s](%s) $ ", time, user, baseName);