char array has some garbage after first loop in c -
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 check; free(fullpath); // close file; }
from output, first round of while loop works fine, file full path correct;
however, second round, file full path contains garbage,
where garbage come from?
how solve this, have tried memset() didn't work.
because fullpath
not initialized. should not use , don't need use strcat()
in situation, if want work make first parameter of strcat()
valid string, can empty string.
right after malloc()
if (fullpath == null) exit(-1); fullpath[0] = '\0';
after that, can use fullpath
first parameter strcat()
.
you see, strcat()
bad use because scans first paramter checking null
terminator but, in case contents of fullpath
undeterminate , might happen first character '\0'
there no guarantee.
you can see how, searching '\0'
terminator every time pass string strcat()
presumably growing inefficient.
also, since going free()
fullpath
inside loop, don't use malloc()
@ all. can use vla (variable length array) or fixed length 1 too. calling malloc()
, free()
not cheap , need strcpy()
or better snprintf()
in case more suitable.
Comments
Post a Comment