Dynamic Memory Allocation Flashcards
What are two functions used for memory allocation in C?
malloc() and calloc()
What does malloc() do?
Allocates a given number of bytes
What does calloc() do?
Allocates memory for a given number of elements, where each element is of a specified number of bytes. Also clears memory (every byte initialized to zero)
What do malloc() and calloc() both do?
Return a pointer to void
What is ‘void’?
A placeholder data type
What does void indicate?
Either no data type, or any data type
What is typecasting?
Explicit data type conversion
What is typecasting commonly used for?
Pointers, to change the data type that a pointer points to. This is possible because all pointers are the same size.
What are the two ways to access contiguous elements?
Using pointer notation and pointer arithmetic, or using array notation (subscripts)
Why deallocate memory?
Otherwise we get a memory leak
Which function deallocates memory at runtime?
Free()
What is a memory leak?
Block of dynamically allocated memory with no pointers to it
How do memory leaks happen?
A pointer gets either clobbered or it moves out of scope
How do we prevent memory leaks?
Always explicitly deallocate memory when you’re done with it, if a function allocates memory then pass the pointer by reference
What is a double pointer?
A pointer variable that contains the address of another pointer variable