← The C Language Lesson 49 of 77 · 10 XP

Allocating memory: malloc and calloc

Theory and problem statement

Machine translation, not yet reviewed by a native speaker.

#include <stdlib.h>

int n = 10;
int *a = malloc(n * sizeof(int));     // n ints, the contents are garbage
if (a == NULL) {                       // there may not be enough memory
    fprintf(stderr, "out of memory\n");
    return 1;
}

int *z = calloc(n, sizeof(int));      // the same, but set to zero

Rules:

  • always calculate the size with sizeof: with malloc(n * sizeof *a) you don't have to remember the type;
  • always check for NULL;
  • malloc returns a void *; in C there's no need to cast it (in C++ there is).

Allocated memory is just a chunk of bytes. You work with it like an array: a[i].

Task. Read n (it may be big — for example, 100,000), allocate an array for n numbers with malloc, read the numbers and print their sum. Don't forget to free the memory.

Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.