Lecture File
dynamic_mem.pdf
Data & Memory
Heap allocation, deallocation, pointer lifetime, and dynamic growth strategy.
File/lecture name: dynamic_mem.pdf Main theme: Dynamic Memory Management in C: Allocation, Deallocation, and Lifetime Safety Prereqs assumed by slides: Basic C syntax (loops, functions, arrays), understanding of stack frames and scope. What this lecture enables you to do:
malloc and deallocate it using free.malloc to request contiguous bytes on the heap; understanding size_t and NULL.free to release memory; the critical rule of setting pointers to NULL after freeing.strchr and generating digit arrays.| Name | Definition | Why it matters | Common confusion / misconception | Tiny example |
|---|---|---|---|---|
| Stack | Memory region for data with lifetime tied to enclosing scope; size known at compile time. | Fast allocation/deallocation; automatic cleanup. | Thinking stack memory is infinite or that it persists after function return. | int arr[10]; (Stack) |
| Heap | Memory region for data whose lifetime is dictated by the programmer; size unknown at compile time. | Allows dynamic sizing; essential for unknown input sizes. | Thinking heap is faster than stack (it is not; it is slower to manage). | int *p = malloc(100); (Heap) |
| malloc | Standard library function to allocate contiguous bytes on the heap. Returns pointer or NULL on failure. |
Enables dynamic memory allocation. | Forgetting to multiply sizeof(type) by count. |
int *p = malloc(sizeof(int)*10); |
| free | Standard library function to deallocate heap memory. Returns void. |
Prevents memory leaks; returns memory to system. | Forgetting to free, or freeing memory that wasn't allocated with malloc. |
free(p); |
| Dangling Pointer | A pointer that stores an address of memory that has already been freed or gone out of scope. | Dereferencing causes undefined behavior (crash/corruption). | Thinking the pointer is still "valid" just because the number isn't zero. | free(p); p = NULL; |
| Memory Leak | Failure to free heap memory when finished with it. | Program consumes more memory over time; eventually crashes. | Thinking "it works now" means it's safe to leak. | malloc without free. |
| size_t | Unsigned integral type guaranteed large enough to store size of any data type. | Used for array lengths and sizes to avoid signed/unsigned mismatch warnings. | Using int for array sizes (can lead to logic errors). |
for (size_t i = 0; ...) |
| Amortized | Average cost per operation over a sequence of operations. | Explains why doubling strategy is efficient despite occasional expensive copies. | Confusing worst-case cost (O(n)) with average cost (O(1)). | Doubling array capacity. |
| Lifetime | The duration during which a variable or memory block is valid and accessible. | Critical for determining if a pointer is safe to use. | Assuming a pointer is safe just because it was initialized. | Returning stack pointer. |
<stdlib.h> is included for malloc and free.sizeof(type) by the number of elements needed.malloc returned NULL (allocation failed).int *arr = malloc(sizeof(int) * 10);
if (arr == NULL) {
// Handle error
}
malloc.NULL after freeing.free.free(arr);
arr = NULL; // Prevents dangling pointer
len == size, the array is full.malloc(sizeof(int) * (size * 2)).len elements from old array to new array.free(arr), arr = newArr, size = size * 2.len < size.free the returned pointer.// BAD: Returns pointer to local stack variable
int *bad(int n) {
int arr[4];
return arr; // Undefined behavior
}
// GOOD: Returns heap pointer
int *good(int n) {
int *arr = malloc(sizeof(int) * 4);
// fill arr
return arr; // Caller must free(arr)
}
| Pattern name | When to use it | Correct minimal example | Common bug + how to avoid it |
|---|---|---|---|
| Safe Allocation | Whenever using malloc. |
int *p = malloc(sizeof(int) * n); |
Forgetting sizeof. Fix: Always use sizeof(type) * count. |
| Safe Free | Whenever using malloc. |
free(p); p = NULL; |
Accessing p after free. Fix: Set p = NULL immediately. |
| Growing Array | When input size is unknown. | if (len == size) { ... double size; ... } |
Growing by 1. Fix: Always double capacity (size * 2). |
| Heap Return | Function creates data to return. | int *ret = malloc(...); return ret; |
Caller forgetting to free. Fix: Caller must free returned pointer. |
| Argument Pointer | Function modifies caller's data. | void func(int *arr, int len); |
Returning pointer to local. Fix: Use heap or pass caller's buffer. |
malloc but never calling free.malloc has a corresponding free.free.NULL after free.sizeof: Using sizeof(arr) instead of sizeof(int).sizeof(type) * count.realloc Avoidance: Slides explicitly advise against realloc for beginners.realloc usage lead to data loss.size_t Usage: Using int for array indices/sizes.size_t for sizes and indices.NULL Check: Not checking if malloc returned NULL.NULL pointer immediately.if (ptr == NULL) { error handling; }.gcc might return NULL for returning stack pointer; clang might overwrite stack.free Return Value: free returns void.free.free(p); (no return value).sizeof on Pointer: sizeof(p) gives pointer size, not array size.sizeof(int) for element size.strchr Example: Returning pointer to found char in string.digits Practice: Returning array of digits.Q: What is the output of the following code?
int *p = malloc(sizeof(int) * 10);
p[0] = 5;
free(p);
printf("%d", p[0]);
A: Undefined behavior (likely crash or garbage). p is a dangling pointer after free.
Q: Why is int arr[1000]; inside main different from int *arr = malloc(sizeof(int)*1000);?
A: The first is on the stack with lifetime tied to main's scope. The second is on the heap with lifetime tied to when free is called.
Q: If you allocate memory with malloc, what must you do before the program exits?
A: You must call free to prevent memory leaks.
Q: What is the time complexity of appending to an array that grows by 1 element each time? A: O(n�) total for n insertions (worst case O(n) per append).
Q: Why do we set a pointer to NULL after calling free?
A: To prevent accidental dereferencing of a dangling pointer.
Q: Can you return a pointer to a local variable from a function? A: No, it is undefined behavior because the stack frame is deallocated when the function returns.
Q: What is the difference between size_t and int?
A: size_t is an unsigned type guaranteed to be large enough for any object size; int is signed and may be smaller.
Q: In the doubling strategy, why do we double the capacity instead of adding 1? A: Doubling ensures amortized constant time insertion (O(1) average), whereas adding 1 leads to O(n) per insertion.
Q: What happens if you call free on a pointer that was never allocated with malloc?
A: Undefined behavior (likely crash).
Q: If a function returns a pointer to heap memory, who is responsible for freeing it? A: The caller is responsible for freeing the memory.
Q: What is the purpose of size_t in malloc?
A: To specify the number of bytes to allocate.
Q: Why is realloc avoided in this lecture?
A: Users often make mistakes with realloc, and there is no analogous function in C++ (so we avoid the habit).
int *ptr = malloc(sizeof(int) * count);free(ptr); ptr = NULL;if (ptr == NULL) { /* error */ }newArr = malloc(sizeof(int) * (size * 2));copy(oldArr, newArr, len);free(oldArr);ptr = newArr;size_t for sizes/indices.free.free heap memory returned by function.malloc returns NULL.std::unique_ptr, std::shared_ptr, std::vector are not covered (slides focus on raw C pointers).realloc: The slides explicitly advise against using realloc for beginners.strchr Implementation: While strchr is used as an example, its full standard behavior (handling NULL input) is not detailed beyond the snippet.digits Function: The practice question for digits is listed but not solved in the slides.primes Function: The practice question for primes is listed but not solved.str_to_int Function: The practice question for str_to_int is listed but not solved.malloc Definition: (Slide 7) "mallocallocates the bytes asked for (if able) and returns a pointer to the first byte allocated."size_t Type: (Slide 8) "sizetis an unsigned integral type that is guaranteed to be large enough to store the size of any possible data type."free Definition: (Slide 11) "Whenever you are finished with heap-allocated memory you must free it | failure to do so is called a memory leak."primes, str_to_int, digits as exercises.yManually curated from summaries/dynamic_mem.txt. Use this page as a study aid and cross-check official slides for grading-critical details.