如何走到这一步的C程序不会崩溃? [英] How come this C program does not crash?

查看:99
本文介绍了如何走到这一步的C程序不会崩溃?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是从书:理解和使用C指针,指向


  

如果存储器被重新peatedly分配然后丢失,则程序
  需要更多的内存,但的malloc不能分配它时,可能会终止
  因为它耗尽了内存。在极端的情况下,操作系统
  可能会崩溃。这在下面的简单的例子说明:


 的char *块;
而(1){
    块=(字符*)malloc的(1000000);
    的printf(清分\\ n);
}


  

变量块被分配从内存
  堆。然而,这种内存不前的另一个块释放
  存储器被分配给它。最终,应用程序将耗尽
  内存和异常终止。


所以,我的问题:
我有这个样本code:

  INT主(INT ARGC,CHAR *的argv []){
    字符*块;
    而(1){
        块=(字符*)malloc的(100000000);
        的printf(清分\\ n);
    }
}

好吧,我希望我的系统运行内存不足,但该程序保持运行,我看到的文字

 分配...

所有的时间?


解决方案

在我的Linux presume?

仅仅因为你会得到一个指针并不意味着你实际上保留内存。你有身体接触的页面,它是你的。

This is from the book: 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.

So to my question: I have this sample code:

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

Well I am expecting my system to run out of memory but the program keeps running and I see the text

Allocating...

all the time?

解决方案

On Linux I presume?

Just because you get back a pointer doesn't mean you actually reserved that memory. You have to physically touch the page for it to be yours.

这篇关于如何走到这一步的C程序不会崩溃?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆