简体   繁体   English

C readdir和struct Dirent分配

[英]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. readdir返回一个指向struct dirent的指针,我已经测试了存储在两个不同指针中的两次对readdir调用是否会修改第一个指针的内容,但不会。

So I guess readdir allocate some memory, am I right ? 所以我想readdir分配了一些内存,对吗?

If so, it should be released, something I never did before... 如果是这样,应该发布它,这是我以前从未做过的事情...

POSIX says that an application must not modify the structure returned by readdir() : POSIX表示应用程序不得修改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. 应用程序不得修改readdir()的返回值所指向的结构,也不得修改该结构内的指针所指向的任何存储区域。 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. 返回的指针以及结构中的指针可能无效,或者结构或存储区域可能被后续对同一目录流上的readdir()的调用所覆盖。 They shall not be affected by a call to readdir() on a different directory stream. 它们不应受到在不同目录流上调用readdir()的影响。

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()关闭目录流。

如果确实分配了任何内存,则调用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. 您应该在readdir之后的目录上调用closedir ,就像在常规文件的fopen之后调用fclose一样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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