Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/69.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 如何有效地处理大型阵列的未使用部分:虚拟内存还是手动?_C_Arrays_Performance_Memory Management - Fatal编程技术网

C 如何有效地处理大型阵列的未使用部分:虚拟内存还是手动?

C 如何有效地处理大型阵列的未使用部分:虚拟内存还是手动?,c,arrays,performance,memory-management,C,Arrays,Performance,Memory Management,考虑以下代码段: 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 (

考虑以下代码段:

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 );

如果目录中有10个文件,则不会使用文件的1014个数组元素,因此接近100%。由于虚拟内存将回收空数组元素用于其他用途,它是否会更有效?

我将向您提供有关内存的信息,让您回答自己的问题:

内存是由不同的部分组成的,在这里,您可以谈论其中的两个部分:计算机提供的部分(映射区域,如
char-cwd[1024]
)和您可以设置属性的部分(未映射区域,如
struct-dirent**file;
),所有这些内存都标在“头”上

程序的最大内存在启动时分配。但它们是两种程序:基本程序和管理员程序。当第二个可以通过添加或抑制一些内存来修改磁头时,第一个只能减少最大内存。所以,如果你有大量的数据(或者有少量的可用内存),当你有一次内存分配的时候,就很难分配2倍的内存

理解malloc的一个很好的练习是尝试创建自己的malloc。这里有一个帮助:


而且,就我而言,如果我能避免使用malloc,我就不会使用它,所以我不会太在意内存泄漏。但是,这取决于每个人。

你的问题似乎基于错误的假设。您的虚拟内存系统不会“回收”空数组元素。虚拟内存系统不知道您没有在这些数组元素中放入任何内容。您要求分配空间,因此它会这样做。注意:
buffer=(struct dirent**)malloc(MAX*ptrsize)此处的大小单位不正确。(不需要强制转换、不需要强制转换等)此外,您的代码也不会像编写的那样工作,因为
readdir()
返回指向临时数据空间的指针。在手册页中,“readdir()返回的数据可能会被同一目录流的readdir()后续调用所覆盖。”。
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++;