Understanding Dynamic Memory Allocation in C

Sep 8, 2024

Dynamic Memory Allocation in C

Introduction

  • Discussed dynamic memory allocation concepts in C.
  • Focus on library functions: malloc, calloc, realloc, and free.

Memory Basics

  • Memory is divided into Stack and Heap.
  • Dynamic memory allocation occurs in the Heap section.

Memory Allocation Functions

1. malloc

  • Most frequently used function for dynamic memory allocation.
  • Signature: void* malloc(size_t size);
  • Parameters:
    • Takes one argument: required size in bytes (positive integer).
    • Returns a void pointer to the allocated memory block.
  • Usage Example:
    • To allocate memory for an integer: int *p = (int*)malloc(sizeof(int));
  • Important:
    • Memory is not initialized (may contain garbage values).

2. calloc

  • Similar to malloc, but more specific.
  • Signature: void* calloc(size_t num, size_t size);
  • Parameters:
    • Takes two arguments: number of elements and size of each element.
    • Initializes allocated memory to zero.
  • Usage Example:
    • To allocate memory for an integer array: int *arr = (int*)calloc(n, sizeof(int));

3. realloc

  • Used to resize a previously allocated memory block.
  • Signature: void* realloc(void* ptr, size_t new_size);
  • Parameters:
    • Pointer to the existing block and the new size required.
  • Behavior:
    • Can either extend the existing memory block or allocate a new one and copy data.
  • Usage Example:
    • int *B = (int*)realloc(A, new_size * sizeof(int));

Memory Deallocation

free

  • Frees memory allocated by malloc, calloc, or realloc.
  • Usage: free(pointer);
  • Important:
    • After freeing, the memory address can still be accessed, but it may lead to undefined behavior.

Code Examples

  • Demonstrated how to dynamically allocate memory for arrays based on user input.
  • Illustrated differences between malloc and calloc regarding initialization.
  • Discussed potential issues with accessing freed memory.

Conclusion

  • Emphasized careful memory management in C.
  • Future lessons will delve deeper into examples and use cases for dynamic memory allocation.