hello I have a code like the one 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 seems working but when I use XCode analyse function, it says “Function call argument is an uninitialized value” and also it sometimes causes my program crash.. when I remove it, then it works fine… Whats wrong with that? Thanks
strcpyandstrcatare used to copy and concatenate strings to an allocated char array.Since
strin not initilized you’re writing somewhere in memory and this is bad because you’re corrupting other data. It may work at that moment but sooner or later you’ll program will crash.You should allocate memory when declaring str:
char str[100];Also,
strcatis not efficient as it needs to search for the string end to know where concatenate chars. Usingsprintfwould be more efficient:sprintf(str, "\t<%s>[%s](%s) $ ", time, user, baseName);Finally, if you can’t guarantee the generated string will fit the array, you’d better use snsprintf.