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 on success (it may differ from the original), NULL on failure. If it fails, the original memory chunk is left untouched.

reallocarray has one real advantage over realloc safety. From the man page on realloc(3), see this snippet:

... However, unlike that realloc() call, reallocarray() fails safely in the case where the  multiplication  would  overflow.   If  such  an  overflow occurs, reallocarray() returns NULL, sets errno to ENOMEM, and leaves the original block of memory unchanged.

Also realize that the reallocarray API is a GNU extension; it will work on modern Linux but should not be considered portable to other OSes.

Finally, consider this: some projects have strict alignment requirements for their data objects; using calloc (or even allocating said objects via malloc(3)) can result in subtle bugs! Later in this chapter, we'll use the posix_memalign(3) API—it guarantees allocating memory to a given byte alignment (you specify the number of bytes)! For example, requiring a memory-allocation to be aligned to a page boundary is a fairly common occurrence (Recall, malloc always returns a memory region that is aligned on an 8-byte boundary).

The bottom line: be careful. Read the documentation, think, and decide which API would be appropriate given the circumstances. More on this in the Further reading section on the GitHub repository.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset