On 8/31/21 12:07 AM, Florian Weimer wrote:
the somewhat common idiom of adjusting internal pointers in the allocation to point to the new allocation is invalid.
Good point. Also, the example call to malloc should check the return value. Something like this, perhaps: char *ptr = malloc(origsize); if (ptr == NULL) return NULL; char *p = ptr + some_random_value(); /* In the following, we presume 'newsize' is not 0. (If 'newsize' is zero, realloc() may return NULL, and that is not an error.) */ ptrdiff_t p_offset = p - ptr; char *nptr = realloc(ptr, newsize); if (nptr == NULL) { /* Handle error; the block pointed to by 'ptr' is still usable. */ } else { /* realloc() succeeded; update 'ptr' and 'p' to point to the (possibly moved) block. 'p += nptr - ptr; ptr = nptr;' would be invalid here, since 'ptr' is invalid immediately after the successful realloc(). */ ptr = nptr; p = nptr + p_offset; }