C Allocate Memory

C Tutorial

1. C Allocate Memory

  • In C Allocate Memory, 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

FunctionDescription
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:

1 2 3 4 5

malloc does not initialize memory, so values could be garbage if not assigned.


4. Using calloc


 

Output:

0 0 0 0 0

calloc initializes allocated memory to zero.


5. Using realloc


 

Output:

1 2 3 4 5
  • realloc resizes memory, preserving existing values.


6. Important Notes

  1. Always check if allocation succeeded:



  1. Always free allocated memory to avoid memory leaks.

  2. Use sizeof() to calculate memory size:

  1. 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.

You may also like...