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

Kor*_*gay 1 c memory malloc

这来自书:理解和使用C指针

如果重复分配然后丢失内存,那么程序可能会在需要更多内存时终止,但malloc因为内存不足而无法分配内存.在极端情况下,操作系统可能会崩溃.这在以下简单示例中说明:

char *chunk; 
while (1) { 
    chunk = (char*) malloc(1000000); 
    printf("Allocating\n"); 
} 
Run Code Online (Sandbox Code Playgroud)

变量块从堆中分配内存.但是,在为其分配另一块内存之前,不释放该内存.最终,应用程序将耗尽内存并异常终止.

所以我的问题: 我有这个示例代码:

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

好吧,我期待我的系统内存不足,但程序一直在运行,我看到了文本

Allocating...
Run Code Online (Sandbox Code Playgroud)

每时每刻?

R S*_*ahu 6

当没有足够的内存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");
    }
}
Run Code Online (Sandbox Code Playgroud)