Dynamic Programming Flashcards
Memory in C
Divided into 5 segments
- Uninitialized data
- Initialized data
- Heap
- Stack
- Code
Stack
Used to store automatics and activation records for functions
-located at the top of writable memory (grows downwards)
Heap
Stores explicitly requested memory which must be dynamically allocated (grows upwards)
Stack frame
Every time a function call is made a new stack frame is created and memory allocated for variables to be used by the function
- if stack and heap continue to grow, all memory available to the process will be exhausted and out of memory error will occur
Reason for dynamic memory
If we don’t know how much memory will be used.
Then it would be inefficient to allocate as much memory as possible
Heap memory
For dynamic allocation when size of not known until run-time
- malloc()
Stack memory
When size is known at compile time
Anonymous variables
Memory addresses in the heap, do not have names
Malloc()
- allocate dynamic memory
- returns memory addresses and takes number of bytes of heap memory to be allocated
- must always check the value returned by malloc()
- have to use typecasting with malloc()
- need #include
Free()
- use to return heap memory no longer needed back to the heap pool
- takes a pointer to the allocated block of memory
Memory leaks
- occurs when heap memory is constantly allocated but is not freed
- systems with automatic garbage collection almost never have memory leaks but it is not in the control of the programmer