Now I try to improve my knowledge of pointers reading "Understanding and Using C Pointers" by Richard Reese.
Here's one code example from this book concerning realloc()
function.
char* getLine(void) {
const size_t sizeIncrement = 10;
char* buffer = malloc(sizeIncrement);
char* currentPosition = buffer;
size_t maximumLength = sizeIncrement;
size_t length = 0;
int character;
if(currentPosition == NULL) { return NULL; }
while(1) {
character = fgetc(stdin);
if(character == '\n') { break; }
if(++length >= maximumLength) {
char *newBuffer = realloc(buffer, maximumLength += sizeIncrement);
if(newBuffer == NULL) {
free(buffer);
return NULL;
}
currentPosition = newBuffer + (currentPosition - buffer);
buffer = newBuffer;
}
*currentPosition++ = character;
}
*currentPosition = '\0';
return buffer;
}
The main idea is to read all symbols into the buffer
until we meet \n
.
We don't know the total number of symbols to read so it's reasonable to use realloc()
function to expand buffer
periodically.
So, to expand buffer
we use:
char *newBuffer = realloc(buffer, maximumLength += sizeIncrement);
In this case realloc()
returns newBuffer
pointer to the expanded buffer.
After that, if realloc()
was invoked successfully, currentPosition
is recalculated as:
currentPosition = newBuffer + (currentPosition - buffer);
QUESTION:
Is it valid to recalculate currentPosition
in such way?
As I know, after realloc()
invocation buffer
pointer is invalidated. (See, for example, this). Any access to the buffer
pointer leads to the undefined behaviour. So... where am I wrong?