请考虑以下代码段:
static int const MAX = 1024; // limit on the number of directory entries
int actual = 0; // counter of directory entires
int ptrsize = sizeof(char*);
int i = 0;
char cwd[1024];
DIR* d;
struct dirent** buffer;
struct dirent** file;
getcwd ( cwd, sizeof ( cwd ) );
d = opendir ( cwd );
buffer = (struct dirent**)malloc(MAX * ptrsize); // allocate the large buffer
/* fill the buffer with dirents for each file in the cwd */
while ( ( buffer[actual] = readdir ( d ) ) != NULL ) actual++;
/* copy the active part of the buffer to the file array and free the buffer */
file = (struct dirent**)malloc(actual * ptrsize);
while ( i < actual ) {
file[i] = buffer[i];
i++;
}
free ( buffer );
使用自动虚拟内存以以下方式实现相同的结果会更有效吗?
static int const MAX = 1024; // limit on the number of directory entries
int actual = 0; // counter of directory entires
char cwd[1024];
DIR* d;
struct dirent* file[MAX];
getcwd ( cwd, sizeof ( cwd ) );
d = opendir ( cwd );
while ( ( file[actual] = readdir ( d ) ) != NULL ) actual++;
如果目录中有 10 个文件,则不会使用 file 的 1014 个数组元素,因此接近 100%。由于虚拟内存将回收空数组元素用于其他目的,它是否仍然更有效?
我会让你用我给你的内存信息来回答你自己的问题:
内存由不同的部分组成,在这里您说的是 2 个部分:计算机给出的那个(映射区域,如您的char cwd[1024]
)和您可以归因的那个(未映射的区域,如您的struct dirent** file;
),所有这些内存都押在"头"上。
程序的最大内存是在程序启动时分配的。但它们是两种程序:基本的程序和管理员的程序。当第二个可以通过添加或抑制一些内存来修改磁头时,第一个只能减少最大内存。因此,如果您有很多数据(或少量可用内存),则很难进行 2 次内存分配,而您可以拥有 1 次。
了解malloc的一个很好的练习是尝试创建自己的malloc。这里有一个帮助:http://www.inf.udec.cl/~leo/Malloc_tutorial.pdf
而且,对我来说,如果我能避免使用 malloc,我就不会使用它,所以我对内存泄漏的关注更少。但是,这取决于每个人。