malloc大内存永远不会返回NULL

时间:2013-05-17 02:46:15

标签: malloc free

当我运行它时,似乎没有问题继续分配内存与cnt超过数千。我不明白为什么 - 我不应该在某个时候获得NULL吗?谢谢!

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>


int main(void)
{
    long C = pow(10, 9);
    int cnt = 0;
    int conversion = 8 * 1024 * 1024;
    int *p;
    while (1)
    {
        p = (int *)malloc(C * sizeof(int));
        if (p != NULL)
            cnt++;
        else break;
        if (cnt % 10 == 0)
            printf("number of successful malloc is %d with %ld Mb\n", cnt, cnt * C / conversion);
    }

    return 0;
}

2 个答案:

答案 0 :(得分:2)

你在Linux上运行吗? Linux有一个非常令人惊讶的功能,称为overcommit。当你调用malloc()时,它实际上并没有实际分配内存,而是当你实际使用那个内存时。 malloc()很乐意让你分配尽可能多的内存,永远不会返回NULL指针。

只有当你真正访问Linux认真对待你的内存并且寻找免费内存给你时才会这样做。当然,实际上可能没有足够的内存来满足它给你的程序的承诺。你说,&#34;给我8GB,&#34;和malloc()说,&#34;当然。&#34;然后你试着写你的指针,Linux说,&#34;哎呀!我撒了谎。在我释放足够的内存之前,我是如何杀掉进程(可能是你的进程)的?&#34;

答案 1 :(得分:0)

您正在分配虚拟内存。在64位操作系统上,虚拟内存几乎可以无限供应。