Skip to main content

Static vs Dynamic Memory Allocation

Static Memory Allocation:

  • Static memory allocation in C refers to the allocation of memory at compile-time.

  • Memory for variables with static storage duration, such as global variables and variables declared with the static keyword, is allocated statically.

Advantages:

  • Simplicity: Memory allocation and deallocation are automatically handled by the compiler.

  • Efficiency: Static memory allocation is generally faster as it doesn't involve runtime overhead.

Disadvantages:

  • Fixed size: The size of statically allocated memory is determined at compile-time and cannot be changed during program execution.

  • Limited flexibility: Static memory allocation does not allow for dynamic resizing or reallocation.

Example

#include <stdio.h>

int globalVariable; // Static memory allocation

int main() {
static int staticVariable; // Static memory allocation

return 0;
}

Explanation:

  • globalVariable and staticVariable are statically allocated variables.
  • The memory for these variables is allocated when the program starts and is deallocated when the program terminates.

Dynamic Memory Allocation:

  • Dynamic memory allocation in C allows for the allocation and deallocation of memory during runtime using functions like malloc, calloc, realloc, and free from the <stdlib.h> header.

Advantages:

  • Flexibility: Dynamic memory allocation allows for dynamic resizing and reallocation of memory as needed during program execution.

  • Variable size: The size of dynamically allocated memory can be determined at runtime, making it suitable for handling varying data requirements.

Disadvantages:

  • Manual memory management: Dynamically allocated memory must be manually deallocated using free to avoid memory leaks.

  • Overhead: Dynamic memory allocation involves runtime overhead for memory allocation and deallocation operations.

Example

#include <stdio.h>
#include <stdlib.h>

int main() {
int* dynamicArray = malloc(5 * sizeof(int)); // Dynamic memory allocation

// ...

free(dynamicArray); // Freeing dynamically allocated memory

return 0;
}

Explanation:

  • malloc is used to dynamically allocate memory for an array of integers.
  • The free function is then used to deallocate the dynamically allocated memory when it's no longer needed.
note

When using dynamic memory allocation, it's important to manage memory properly to avoid memory leaks or accessing freed memory, which can lead to bugs and undefined behavior.