Home > Software engineering >  Explanation of "realloc doesn't require that ptr point to a memory but in practice does.&q
Explanation of "realloc doesn't require that ptr point to a memory but in practice does.&q

Time:01-01

I am reading about the realloc function, i.e.

void *realloc(void *ptr, size_t size);

and the author of the textbook I'm reading (K.N. King "C Programming a Modern Approach", 2nd edition, p.421, last paragraph), at some point writes

Although realloc doesn't require that ptr point to memory that's being used as an array, in practice it usually does.

My apologies if this is trivial, but I'm confused. My obvious question is: how? Unfortunately, the author doesn't go any further on this.

Can you provide an expanded explanation, perhaps using a simple example?

CodePudding user response:

The “it” in “in practice it usually does” means ptr. The clause is saying that we usually use realloc with memory that is being used as an array.

The most common use of realloc is to reallocate space for an array: We initially allocate some memory, process input, find that processing the input requires a larger array, and so use realloc to increase the space. This is not a requirement of realloc; it is the nature of how it is used.

It is not the only possible use. Another is we might have some set of related structures, such as struct Square, struct Circle, struct Polygon, and so on, all with some common initial element, struct Shape. We might initially allocate space for struct Shape so that we can do some initial processing of the shape before we know what shape it will be. Later, when the specific shape is done, we might use realloc to grow the space from that needed for struct Shape to that needed for struct Square.

CodePudding user response:

He is merely (and probably unnecessarily) pointing out that typically if you are resizing an allocation, it will be for storing a different number of objects of the same type (i.e. an array). It really does not need saying.

Situations where that might not be the case may occur, but are "unusual". For example you might implement a string "class" using a structure such as:

typedef struct
{
    size_t length ;
    size_t capacity ;
    char strdata[1] ; // gcc allows [0] here by extension
} string_t ;

Now you can dynamically allocate or reallocate a single object of type string_t to accommodate a string of variable length using a size sizeof(string_t) string_capacity. By virtue of being at the end of the structure, you can "overrun" the strdata array into the dynamically allocated space.

It is perhaps all a bit "tricksy" and anyone doing that has probably long passed needing realloc() explaining, so it might have been better for the author to have said nothing, since the typical usage is also the obvious usage, and it would probably never occur to a novice to use it any other way.

  • Related