I'm new to memory management and have just begun to look into it. From what I know:
I have looked at quite a few sources on this topic but am unsure about the heap mainly. Some sources say that data stored in the heap stays there after the program ends until you call free(). Other sources say that both heap and stack are cleared once the program end. If this is true, where is data stored after runtime? Also why do I need to free() my data if malloc() creates data on the heap which is automatically cleared at the end of the program.
Any other information and recommendations on memory basics are appreciated.
Stack memory is where automatic data is stored on most systems: data defined locally in function bodies that is not explicitly qualified as static
.
Heap memory is where malloc()
and friends get blocks of data from. It is allocated to the program by the operating system and is usually automatically deallocated when the program ends. There are special cases where the heap memory is not freed when the program ends, if there is no operating system, but these cases are very rare.
Blocks allocated from the heap cannot always be reallocated to a different size, and such reallocation may involve moving the data to a different address, which is confusing and error prone, so changing the size of an allocated object is somewhat of a misnomer.
There is no hard requirement to free()
the objects allocated from the heap, but it is considered good style, and in some cases it is very important:
if the program runs for a long time or uses a lot of memory, freeing the blocks that are no longer needed helps reduce the memory footprint. Not freeing them may cause the system to run out of memory or start swapping and make the system unstable.
freeing all allocated blocks upon exit is a good way to check that the program accounts for all allocated blocks, which can be verified with specific tools such as valgrind.