In: Computer Science
What happens if the stack and heap segments collide (i.e., one overwrites part of the other)? Why is this dangerous? How would you prevent it?
Answer:
If the stack grows into the heap, then the C compiler will silently start to overwrite the heap's data structures without keeping any concern. On recent and modern Operating Systems, there are one or more virtual memory guard pages which restrict the stack from growing indefinitely. And as long as the amount of memory in the guard pages is at least as large as the size of the growing procedure's activation record, the Operating System will assure us with a segfault.
And if the heap grows into the stack, then the operating system must beware of the situation as some sort of system call will fail. The implementation of malloc() almost certainly notices the failure and returns NULL. Anything after that depends upon the user then.
Also please note this is platform dependent. Doesn't happen everywhere. As in a lot of places stack and heap are allocated at separate pages.
It cannot be prevented if you have code that is in a runaway loop, creating huge amount of data that overruns the available memory. Therefore Check all places where you are in a for or while loop to be sure that they can exit. Then this collision can be prevented.
***********************************************************************************************************************************************
Hope this helps, Thanks :-)