<aside>
<img src="/icons/home_green.svg" alt="/icons/home_green.svg" width="40px" />
Back to Home
</aside>
https://jennychen9827sbu.github.io/CAD281/malloc.html
What is malloc?
malloc (memory allocation) is a function in C used to dynamically allocate memory from the heap during runtime.
Why use malloc?
- You don’t know the size of data at compile time (e.g. user input).
- You want to allocate memory only when needed (save space).
- Arrays with flexible size (e.g.
int* arr = malloc(n * sizeof(int));).
Where is the memory allocated?
- Memory is taken from the heap (a large pool separate from the stack).
- Returned as a pointer to the beginning of the allocated block.
When to use malloc?
- When the size of the data structure is not known beforehand.
- When large data needs to persist after a function ends.
- For structures like linked lists, trees, etc.