Dynamic Memory Allocation Flashcards
Why are variable sized arrays problematic in C?
Not all versions of C support them
They are stored in the stack which has a limited amount of space
Where are local variables and function parameters stored?
On the stack
What is the heap used for?
Dynamic memory allocation at run time
What argument does malloc take?
The number of bytes to reserve on the heap
What does malloc return?
It returns a pointer to the memory space it has reserved
It returns a pointer of type void*
Who is responsible for freeing memory that has been reserved using malloc?
The programmer
This is done using the free(pointer)
function
Where are global variables stored?
In Static Data
How is memory in the heap accessed?
It can only be accessed through pointers.
How would we create a 2d int array that is of size AxB?
- Create a pointer to an array of pointers.
int** 2d_arr = malloc(A * sizeof( int* ));
- Assign a pointer to an int array to each element in the pointer array
for all pointers in the pointer array:
What are two important things to remember when using malloc?
- Always check that malloc hasn’t returned -1, indicating a failure
- Remember to free the memory after it has been used, using the free(pointer) function