Memory Allocation: Difference between revisions

m
new/delete do not necessarily use the same freestore/heap as malloc/free
(Make it more likely for code to work “out of the box”, add notes about <stdint.h> not present on old GCC)
m (new/delete do not necessarily use the same freestore/heap as malloc/free)
 
Line 5:
The normal way to allocate memory in C on a modern system is to use malloc and free, provided by the standard C library. These functions are not magic! They use various data structures (some clever, some simple) to keep track of which ranges of memory are in use, and which blocks of memory are available.
 
'''Note:''' In C++, new/delete are justsimilar wrappers aroundto malloc/free, and std::unique_ptr / std::shared_ptr (by default) are wrappers around new/delete. So the same problems with malloc and free also apply to C++.
 
The main problem that malloc/free must face is that you can allocate memory and free memory however you like. This can cause ''heap fragmentation,'' which is when you have free memory, but the free memory is “fragmented” into many small chunks. If you need to allocate a larger chunk of memory, you can’t use the small chunks. If heap fragmentation gets bad enough, malloc/free will start failing, and your game won't be able to continue running.