c - 为什么这个 C 程序不会崩溃?

标签 c memory malloc

这本书来自:Understanding and Using C Pointers

If memory is re‐ peatedly allocated and then lost, then the program may terminate when more memory is needed but malloc cannot allocate it because it ran out of memory. In extreme cases, the operating system may crash. This is illustrated in the following simple example:

char *chunk; 
while (1) { 
    chunk = (char*) malloc(1000000); 
    printf("Allocating\n"); 
} 

The variable chunk is assigned memory from the heap. However, this memory is not freed before another block of memory is assigned to it. Eventually, the application will run out of memory and terminate abnormally.

那么对于我的问题: 我有这个示例代码:

int main(int argc, char *argv[]){
    char *chunk; 
    while (1) {
        chunk = (char*) malloc(100000000);
        printf("Allocating\n"); 
    }
}

好吧,我希望我的系统内存不足,但程序继续运行,我看到了文本

Allocating...

一直?

最佳答案

当内存不足时,malloc 可能会返回 NULL。为此添加一个支票。

while (1) {
    printf("Allocating\n"); 
    chunk = malloc(100000000);
    if ( chunk == NULL )
    {
       printf("Memory allocation not successful.\n");
    }
    else
    {
       printf("Memory allocation successful.\n");
    }
}

关于c - 为什么这个 C 程序不会崩溃?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29610445/

相关文章:

Scipy径向基函数(scipy.interpolate.rbf)中的Python MemoryError

c - 具有函数 c 的动态矩阵

c - 汇编与 C 代码比较

c - 生成文件说明

c - glviewport 和 win32 api

c - 即使 Proc 分配的内存少于 ulimit 限制的内存,它也会崩溃

c# - 通过接口(interface)调用对象的方法时的内存利用率?

c++ - ExtAudioFileOpenURL 泄漏

c - malloc 后访问冲突

计算数字在二维数组 C 中出现的次数