C MemoryLesson 43Free preview
C Memory Management
This lesson is part of C · All levels
Summary
C gives full control over memory: local variables live in the stack, whereas big data is allocated in the heap via malloc, calloc, realloc, and must be returned free. The classic bug in C is memory leakage because it forgets free and use-after-free because it uses memory that's already been released. A good practice is to check the allocation results against NULL, pair each allocation with free, and set the pointer to NULL after it is released.
Key points
- Malloc(n) allocates n empty bytes; calloc(n, size) allocates while setting zero; realloc changes size.
- Always check the allocation results against NULL before using the pointer.
- Free only for the malloc, calloc, or realloc result pointer, not any address or local variable address.
- A memory leak occurs when a pointer to the allocation is lost without being in-free; a dangling pointer is a pointer that indicates memory is already free.
- The data in the heap lives until it is released free, unlike the local variable that is lost when the function is completed.
Full lesson
Code examples and quizzes
Full lessons, code examples, and quizzes are available to subscribers. 5 questions.