堆内存占满会发生什么?添加空指针判断的循环代码会有何表现?
Hey there! Let's walk through your two questions clearly, like we're chatting through a coding problem together.
问题1:当堆内存被占满时,会出现什么情况?
Let's break down the sequence of events step by step:
- When you call
malloc()and the heap doesn't have enough contiguous free space, the C runtime will first try to expand the heap (using system calls likebrk()ormmap()on Unix-like systems, or equivalent mechanisms on Windows). - If the system has no more available physical or virtual memory to allocate to the process,
malloc()will returnNULL—this is the standard behavior defined by the C language spec. - What happens next depends entirely on your code:
- If your code doesn't check for
NULLand tries to dereference the pointer (like writing to*p), this triggers undefined behavior. Most often, this leads to a segmentation fault (a crash) because you're trying to access memory that's not allocated to your process. - On some systems with memory overcommit enabled, the OS might let
malloc()return a non-NULL pointer even if no actual memory is available. But when you try to use that memory, the OS will trigger an out-of-memory (OOM) killer, which will terminate your process (or another memory-heavy process to free up space).
- If your code doesn't check for
问题2:以下代码场景中,若添加
if (p == NULL) { break; }语句,程序会有何表现? First, let's look at the corrected modified code (I added a missing header that's required for malloc()):
#include <stdio.h> #include <stdlib.h> // Critical: malloc() is declared here void main() { int *p; while (1) { p = malloc(1024); // allocating 1KB chunks in infinite loop if (p == NULL) { break; } } }
Here's how the modified program behaves:
- The loop keeps calling
malloc(1024)to grab 1KB chunks of memory each iteration. - Eventually, when the heap can't be expanded anymore and the system has no free memory left,
malloc()returnsNULL. - The
if (p == NULL)check catches this, runs thebreakstatement, and exits the infinite loop. - Since there's no code after the loop, the
main()function returns, and the program terminates gracefully—no crash, no infinite loop stuck trying to allocate memory forever.
A quick heads-up: This program will still consume as much memory as the system allows before exiting, so don't run it on a machine where you need to keep other apps running smoothly!
内容的提问来源于stack exchange,提问作者Utkarsh Patel
相关产品推荐
相关产品推荐

