5 ms·
> Stack overflows seems opaque to me, while preallocating memory (malloc) has mechanism to signal failures for proper handling. On Linux (and probably on other
by bnegreve 12y ago
> Stack overflows seems opaque to me, while preallocating memory (malloc) has mechanism to signal failures for proper handling.
On Linux (and probably on other OSs) it's not easy to detect that the system is out heap memory because of lazy memory allocation policies.
Physical memory is not allocated when you call malloc() but when you first read or write the corresponding memory page.
Because of this, malloc() does not necessarily return NULL even if there isn't enough memory available on the system at the time you called malloc(). But if the system is still out of memory when your first access the allocated memory, your program will crash with a segfault.
So in absence of extra precaution, using heap memory isn't any safer than using stack memory.