C Memory Management

1. Memory in C

C programs use two main types of memory:

Memory Type Description
Stack Stores local variables, function calls, and automatic data. Managed automatically.
Heap Stores dynamically allocated memory. Managed manually using malloc/free.

2. Static vs Dynamic Memory Allocation

Type Description Example
Static Memory size known at compile time. Allocated automatically on stack. int a[10];
Dynamic Memory size determined at runtime. Allocated manually on heap. malloc(), calloc()

3. Dynamic Memory Allocation Functions

C provides the following functions in <stdlib.h>:

Function Description
malloc(size_t size) Allocates memory of given size in bytes. Returns void*.
calloc(size_t n, size_t size) Allocates memory for n elements, initializes to 0.
realloc(void *ptr, size_t size) Resizes previously allocated memory.
free(void *ptr) Frees memory allocated on heap.

4. Example: Using malloc


 

Output:

1 2 3 4 5

5. Example: Using calloc


 

Output:

0 0 0 0 0

6. Example: Using realloc


 

Output:

1 2 3 4 5

7. Memory Leaks

  • Memory leak occurs when allocated memory is not freed.

  • Always use free() after dynamic allocation.

  • Example:


8. Key Points About C Memory Management

  1. Stack memory: automatic, fast, limited size.

  2. Heap memory: manual, dynamic, larger but slower.

  3. Use malloc, calloc, realloc for dynamic allocation.

  4. Use free() to release heap memory.

  5. Avoid memory leaks by freeing allocated memory.

  6. Proper memory management is crucial in embedded systems, large applications, and performance-critical programs.

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *