简体   繁体   中英

C readdir & struct dirent allocation

readdir return a pointer to a struct dirent , I have tested if two calls to readdir stored in two different pointers modify the first pointer content, it doesn't.

So I guess readdir allocate some memory, am I right ?

If so, it should be released, something I never did before...

POSIX says that an application must not modify the structure returned by readdir() :

The application shall not modify the structure to which the return value of readdir() points, nor any storage areas pointed to by pointers within the structure. The returned pointer, and pointers within the structure, might be invalidated or the structure or the storage areas might be overwritten by a subsequent call to readdir() on the same directory stream. They shall not be affected by a call to readdir() on a different directory stream.

So whether it internally allocates memory or uses a static buffer depends on how how a specific implementation implements. All you need to do is respect the contract that the function requires. That is, you must not attempt to modify it and call closedir() to close the directory stream.

如果确实分配了任何内存,则调用closedir( http://linux.die.net/man/3/closedir )将为您释放它

Yup, it should be released. You should call closedir on a directory after readdir , just like you call fclose after fopen for regular files.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM