在 Linux 中,内核在我们实际使用该内存之前不会分配任何物理内存页,但我在这里很难找到它实际上分配此内存的原因:
for(int t = 0; t < T; t++){
for(int b = 0; b < B; b++){
Matrix[t][b].length = 0;
Matrix[t][b].size = 60;
Matrix[t][b].pointers = (Node**)malloc(60*sizeof(Node*));
}
}
然后我访问这个数据结构,像这样向它添加一个元素:
Node* elem = NULL;
Matrix[a][b].length++;
Matrix[a][b]->pointers[ Matrix[a][b].length ] = elem;
本质上,我在旁边运行我的程序时使用 htop,如果我增加 no,Linux 会分配更多内存。 “60”我在上面的代码中有。为什么?当第一个元素添加到数组时,它不应该只分配一页吗?
最佳答案
这取决于您的 Linux 系统是如何配置的。
这是一个简单的 C 程序,它尝试分配 1TB 内存并触及其中的一些内存。
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
int main()
{
char *array[1000];
int i;
for (i = 0; i < 1000; ++i)
{
if (NULL == (array[i] = malloc((int) 1e9)))
{
perror("malloc failed!");
return -1;
}
array[i][0] = 'H';
}
for (i = 0; i < 1000; ++i)
printf("%c", array[i][0]);
printf("\n");
sleep(10);
return 0;
}
当我在其旁边运行 top 时,它表示 VIRT 内存使用量达到 931g(其中 g 表示 GiB),而 RES 仅达到 4380 KiB。
现在,当我通过 /sbin/sysctl -w vm.overcommit_memory=2
更改我的系统以使用不同的过量使用策略并重新运行它时,我得到:
malloc failed!: Cannot allocate memory
因此您的系统可能使用了与您预期不同的过度使用策略。更多信息请阅读 this .
关于c++ - Linux 真的分配了它不应该在 C++ 代码中的内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28920269/