Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

A heap is a data structure used by the malloc() and free() functions to find appropriately-sized chunks of RAM to give to the rest of the program.

The defining feature of heap-allocated memory is that it's persistent up the call stack; a common newbie error in C is to return a pointer to something allocated on the stack, which will become invalid the instant the other function sees it: If a() calls b(), everything in b()'s section of the call stack is cleaned up when b() returns to a(), so if a() tries to dereference a pointer to something b() allocated on the stack, the program will die.

The flip side is that programmers have to manage this by hand, which is the cause of memory leaks. Garbage collection is used to mitigate this; to, at the very least, turn a program from one with quickly-growing memory usage into one with slow-growing memory usage.



Technically (at least on x86 and ARM), if b() allocates memory on the stack and returns a pointer to a(), as long as the pointer is dereferned immediately after the call the b(), the value should still be the same. It's not something you should count on (and purposely relying on it is a sin), but it won't kill your program.

http://ideone.com/oIZXTY


It is an undefined behavior. It is very likely that something will go wrong, especially when optimizations are on. It is something you should never really on.


Why would the program die? It can work depending on what happens between the invocations [1].

[1]: http://codepad.org/Z7Ojq9ml




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: