I have the following code. It gives me a problem with free memory, but I haven’t figured out what exactly the problem is. It seems that getpwuid(buf->st_uid); is not getting along with readdir(dirh); or with stat functions. Does anyone know why?
buf = (struct stat*) malloc(sizeof(struct stat));
for (dirp[i] = readdir(dirh); dirp[i] != NULL; dirp[++i] = readdir(dirh)){
ptr=(char *)malloc(sizeof(strlen(mydir)));
ptr=strdup(mydir);
strcat(ptr,dirp[i]->d_name);
stat(ptr,buf);
//modos();
getpwuid(buf->st_uid);
printf("\t%s\n",ptr);
//we free the buf memory
}
free(buf);
closedir(dirh);
You don’t allocate enough space for the string.
You do an unorthodox length calculation which ignores the actual length of ‘mydir’; you then make a good copy of the directory name (but leak the memory previously allocated); you then concatenate the name over the end of the space allocated by
strdup(), which is always bad. If you omitted thesizeof(), then you would be allocating one byte too few for a null terminated directory string.You also should not cache the separate return values from
readdir()because it generally returns a pointer to the same bit of memory each time. You are certainly not authorized to assume that it does otherwise.You are also trampling over freed memory if you really release buf inside the loop; you allocate just once, and free many times.
Normally, you would not bother to allocate the
bufat all; it is not that big a structure.You also don’t self-evidently have a slash separator between the directory name and the file name component; that might not matter if you’ve ensured that
mydirhas one on the end.Here is a simple program that more or less does what is necessary.
Note: The calculation of
dlenis correct, but only because the value ofmydirincludes the trailing slash. If the directory name did not include that trailing slash, the code would need changes to the length calculation and to formatting the composite name (thestrcpy()strcat()sequence). Beware!