codegurukool.com · Free coding tutorials & online compiler

Home › C Tutorial › C allocate and access memory

C allocate and access memory

malloc gives memory at run time.

malloc(bytes) returns a pointer, or NULL on failure. Use sizeof, check the result, and use it like an array.

Example code

#include <stdio.h>
#include <stdlib.h>
int main() {
  int *a = malloc(3 * sizeof(int));
  if (a == NULL) return 1;
  for (int i = 0; i < 3; i++) a[i] = i * 10;
  printf("%d %d\n", a[1], a[2]);
  free(a);
  return 0;
}

Run this code in the online editor

← C enumsC reallocate memory →