CHAPTER 23 / 26
C Dynamic Memory
Learn malloc(), calloc(), realloc() and free() for dynamic memory.
01 — Syntax
int *p = malloc(size);\nfree(p);
02 — Example
#include <stdio.h>
#include <stdlib.h>
int main() {
int *p = malloc(5 * sizeof(int));
if (p != NULL) {
p[0] = 100;
printf("%d", p[0]);
free(p);
}
return 0;
}03 — Important Points
- Dynamically allocated memory must eventually be released.
- Check allocation results before dereferencing.
04 — Common Mistakes
- Forgetting free().
- Dereferencing NULL.
- Allocating the wrong amount of memory.
05 — Real-World Use
Dynamic memory is useful when the amount of data is known only at runtime.
06 — Practice
Create a small program that demonstrates the main idea of C Dynamic Memory.