Patrick Patrick - 3 months ago 10
C Question

char array has some garbage after first loop in c

enter image description here

while( (entry = readdir(dir_pointer)) != NULL)
{
char *fullpath = malloc(dir_len + strlen(entry->d_name) + 2);
printf("\nfullpath: %s\n", fullpath);
strcat(fullpath, dir); // concatenate file directory;
printf("\ndir: %s\n",fullpath);
strcat(fullpath, "/"); // concatenate "/";
strcat(fullpath, entry->d_name); // concatenate filename;
printf("\nfullpath: %s\n", fullpath); // print to check;

free(fullpath);
// close the file;



}


From the output, the first round of while loop works fine, the file full path is correct;

However, for the second round, the file full path contains some garbage,

Where does the garbage come from?

How to solve this, I have tried the memset() but it didn't work.

Answer

Because fullpath is not initialized. You should not use and you don't need to use strcat() in this situation, but if you want it to work simply make the first parameter of strcat() a valid string, it can be an empty string.

Right after malloc()

if (fullpath == NULL)
    exit(-1);
fullpath[0] = '\0';

after that, you can use fullpath as the first parameter to strcat().

You see, strcat() is bad to use because it scans the first paramter checking for the null terminator but, in your case the contents of fullpath are undeterminate and it might happen that the first character is a '\0' but there is no guarantee.

You can see how, searching for the '\0' terminator every time you pass the string to strcat() which is presumably growing will be inefficient.

Also, since you are going to free() fullpath inside the loop, don't use malloc() at all. You can use a VLA (Variable length array) or a fixed length one too. Calling malloc() and free() is not cheap and you will already need strcpy() or better snprintf() in this case is more suitable.