这本书来自: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/