C Memory Management

What is Memory Management?

Memory management in C refers to manually controlling memory allocation and deallocation.

Unlike many languages, C does not automatically manage memory for you.

Stack vs Heap

There are two main types of memory in C:

  • Stack: Automatically managed, used for local variables
  • Heap: Manually managed, used for dynamic memory
Loading...
Output:

malloc()

malloc() allocates memory but does not initialize it.

Loading...
Output:

calloc()

calloc() allocates memory and initializes it to zero.

Loading...
Output:

realloc()

realloc() resizes previously allocated memory.

Loading...
Output:

free()

free() releases allocated memory back to the system.

Failing to free memory causes memory leaks.

Loading...
Output:

Dynamic Arrays

You can dynamically allocate arrays using malloc or calloc.

Loading...
Output:

Checking for NULL

Always check if memory allocation was successful.

Loading...
Output:

Memory Leaks

A memory leak happens when allocated memory is not freed.

Loading...
Output:

Dangling Pointers

A dangling pointer points to memory that has already been freed.

Loading...
Output:

Best Practices

  • Always free memory
  • Check for NULL
  • Set pointer to NULL after freeing
Loading...
Output:

Real-World Example

Dynamic memory is commonly used when the size of data is not known at compile time.

Loading...
Output:

Why Memory Management is Important

Memory management is one of the most important features of C.

  • Efficient use of memory
  • Essential for systems programming
  • Used in operating systems and embedded systems

Common Mistakes

Be careful with these:

  • Not freeing memory
  • Using freed memory
  • Incorrect memory size allocation

Practice

Dynamically allocate an array, store values, print them, and free memory.

Loading...
Output:

Need Help?