The reallocarray API

A scenario: you allocate memory for an array using calloc(3); later, you want to resize it to be, say, a lot larger. We can do so with realloc(3); for example:

struct sbar *ptr, *newptr;ptr = calloc(1000, sizeof(struct sbar)); // array of 1000 struct sbar's[...]// now we want 500 more!newptr = realloc(ptr, 500*sizeof(struct sbar));

Fine. There's an easier way, though—using the reallocarray(3) API. Its signature is as follows:

void *reallocarray(void *ptr, size_t nmemb, size_t size);

With it, the code becomes simpler:

[...]// now we want 500 more!newptr = reallocarray(ptr, 500, sizeof(struct sbar));

The return value of reallocarray is pretty identical to that of the realloc API: the new pointer to the resized memory chunk ...

Get Hands-On System Programming with Linux now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.