Dynamic Memory Allocation: malloc
allocated memory at runtime
Stack vs Heap:
Stack Frames store per function call:
Local variables, parameters, return value
Heap stores:
Dynamic allocations... at runtime
Must be explicitly de-allocated using free after the program no longer needs the memory.
Otherwise a memory leak will occur If the program loses track of an allocation, it is unable to be deallocated
Two functions and a special operator allow us to use the memory of the heap:
The type size_t is simply a typedef for an unsigned integer
size_t is used to count bytes
Often, we use the sizeof operator to help calculate the number of bytes required by the dynamic allocation
Using malloc
malloc requires passing in the number of bytes that will be used by program.
This can be done by using the sizeof to get the number of bytes for a variable or structure to be stored
malloc will returns an address (a pointer) of the first element in the block of memory... or null (zero) if the allocation is not possible
Allocate a block of 5 ints:
Store the pointer to the first element in the array once it has been allocated.
Then treat the block of memory like the array that it is
When allocate 2D blocks of memory:
Just calculate the number of bytes required... and ask malloc for the allocation
Remember! At runtime an array is just a pointer:
print the same %p value for both block_of_data and p_first
Remember we can treat dynamically allocated memory as an array if we want:
malloc () gives us the memory until we give it back with free ():
If we forget to deallocate, we create a memory leak!
This will make our program crash eventually, or at least diminish our computer's capabilities temporarily
Exercise:
Requirement (9x05c - Memory Sharing)
Implementation
Requirement (9x06c - Bad Array Passing)
Implementation
This program is designed for printing the star-time according to the assignnments.
Errors Encountered
Debug
Because in the program has used start_time three times!
Test
Requirement (9x07d - C-String Analyser)
Implementation
Test
Requirements (9x08a)& Design
Implementation
Test
Requirements (9x08c - num_spaces)
Implementation
Test
Error occurred
Debug
Program will never enter this loop.
Lesson Learn
Distinguish the index or array[index].
Requirement (10x08a - Recursive Movie)
Implementation
Test
10x10a - ASCII Card