Dynamic Memory Allocation
Dynamic Memory Allocation
Intro
In c so far we have looked at static memory allocation.
Memory can be allocated inside a stack frame but deletion is difficult.
How to actually do it
sizeof
Returns the size of a datatype in bytes (not nibbles ).
Benefits:
Don’t have to remember sizes of data types.
Increased portability since not all systems have same size of int, float etc.
(2008 data not up to date,
but illustrates the point)
Malloc:
Allocates memory from heap and returns a pointer to it in the heap.
Memory is not in stack frame.
Tracks size of allocated memory.
If allocation fails, returns ptr = NULL.
System does not track memory.
All allocated memory must be freed!
Failure to do this causes the memory to be lost
This is known as a memory leak.
Exiting program frees all memory
Free:
De-allocates memory stored in heap.
Uses information stored by malloc to decide how much it needs to free.
Free should be used on all dynamically allocated memory when leaving the main program.
There are cases where you may not want to free when you leave a function.
Example
/docProps/thumbnail.jpeg