Labs ICT
โญ Pro Login

Dynamic Memory

So far you've declared all your variables up front โ€” the compiler knows exactly how much memory you need. But what if you don't know until the program runs? That's where dynamic memory comes in: asking for memory at runtime.

malloc โ€” Memory Allocate

malloc reserves a block of memory and returns a pointer to it. The memory is uninitialized โ€” it could contain anything. Pass the number of bytes you need.


#include 
#include 
int main() {
  int *arr;
  int n = 5;
  arr = (int *)malloc(n * sizeof(int));
  if (arr == NULL) {
    printf("Allocation failed\n");
    return 1;
  }
  for (int i = 0; i < n; i++) {
    arr[i] = i * 10;
  }
  for (int i = 0; i < n; i++) {
    printf("%d ", arr[i]);
  }
  printf("\n");
  free(arr);
  return 0;
}
    
Try it Yourself โ†’

calloc โ€” Clear Allocate

calloc is like malloc but with two differences: it takes number of elements and element size separately, and it zeroes out all the memory before returning.


#include 
#include 
int main() {
  int *arr;
  int n = 5;
  arr = (int *)calloc(n, sizeof(int));
  if (arr == NULL) {
    printf("Allocation failed\n");
    return 1;
  }
  for (int i = 0; i < n; i++) {
    printf("%d ", arr[i]);
  }
  printf("\n");
  free(arr);
  return 0;
}
    
Try it Yourself โ†’

realloc โ€” Resize Allocate

Need a bigger (or smaller) array? realloc resizes an existing block of memory, preserving the old data up to the minimum of the old and new sizes.


#include 
#include 
int main() {
  int *arr;
  int n = 3;
  arr = (int *)malloc(n * sizeof(int));
  arr[0] = 1; arr[1] = 2; arr[2] = 3;
  n = 5;
  arr = (int *)realloc(arr, n * sizeof(int));
  arr[3] = 4; arr[4] = 5;
  for (int i = 0; i < n; i++) {
    printf("%d ", arr[i]);
  }
  printf("\n");
  free(arr);
  return 0;
}
    
Try it Yourself โ†’

free โ€” Give Memory Back

Every malloc, calloc, or realloc must be matched with a free. Forgetting to free causes memory leaks โ€” your program hoards memory until it crashes or the OS kills it.


#include 
#include 
int main() {
  int *ptr = (int *)malloc(sizeof(int));
  *ptr = 100;
  printf("%d\n", *ptr);
  free(ptr);
  ptr = NULL;
  return 0;
}
    
Try it Yourself โ†’

๐Ÿงช Quick Quiz

Which function allocates memory on the heap?