Pointers (Malloc() and free()) Flashcards
What is a pointer?
Recall that the value of a pointer is a memory address. Dereferencing (*) a pointer gives you the value being held in that memory address.
What does malloc stand for?
Memory allocation
What does malloc() do?
Dynamically allocates a block of memory during runtime.
Returns a pointer to the first byte of the allocated memory.
Memory is not initialized; it contains garbage values.
void* malloc(size_t size);
What does free() do?
Deallocates memory previously allocated using malloc()
Prevents memory leaks by releasing unused memory.
void free(void* ptr);
What are some common errors when using malloc and/or free?
Forgetting to use free() with malloc()
Accessing memory after it’s been freed.
Not checking for NULL after malloc().
Incorrect memory allocation size (e.g., forgetting to use sizeof()).