[prev] 63 [next]

The malloc() function (cont)

Usage of malloc() should always be guarded:

int *vector, length, i;
…
vector = malloc(length*sizeof(int));
// but malloc() might fail to allocate
assert(vector != NULL);
// now we know it's safe to use vector[]
for (i = 0; i < length; i++) {
	… vector[i] …
}

Alternatively:

int *vector, length, i;
…
vector = malloc(length*sizeof(int));
// but malloc() might fail to allocate
if (vector == NULL) {
	fprintf(stderr, "Out of memory\n");
	exit(1);
}
// now we know its safe to use vector[]
for (i = 0; i < length; i++) {
	… vector[i] …
}

  • fprintf(stderr, …) outputs text to a stream called stderr (the screen, by default)
  • exit(v) terminates the program with return value v