C Allocate Memory
1. What is Dynamic Memory Allocation?
-
In C, dynamic memory allocation allows programs to request memory from the heap at runtime.
-
Unlike static memory (fixed at compile-time), dynamic memory can grow or shrink as needed.
-
Requires manual management using allocation and deallocation functions.
2. Memory Allocation Functions in C
| Function | Description |
|---|---|
malloc(size_t size) |
Allocates memory of specified size in bytes. Content is uninitialized. |
calloc(size_t n, size_t size) |
Allocates memory for n elements, each of size bytes, and initializes to 0. |
realloc(void *ptr, size_t size) |
Resizes previously allocated memory. Preserves existing content. |
free(void *ptr) |
Frees previously allocated memory. |
3. Using malloc
Output:
mallocdoes not initialize memory, so values could be garbage if not assigned.
4. Using calloc
Output:
callocinitializes allocated memory to zero.
5. Using realloc
Output:
-
reallocresizes memory, preserving existing values.
6. Important Notes
-
Always check if allocation succeeded:
-
Always free allocated memory to avoid memory leaks.
-
Use
sizeof()to calculate memory size:
-
Dynamic memory is stored in the heap, not the stack.
7. Key Points
-
malloc→ allocate uninitialized memory. -
calloc→ allocate zero-initialized memory. -
realloc→ resize previously allocated memory. -
free→ release memory back to the system. -
Dynamic allocation is essential for flexible programs that need variable-size data structures like arrays, linked lists, or trees.
