nikhil chaubey
nikhil chaubey

Reputation: 401

Resizing the array, code from a book in C

I am currently trying to understand pointers from this book,
http://shop.oreilly.com/product/0636920028000.do

In chapter Pointers and arrays, under this heading Using the realloc Function to Resize an Array page 87 author has given a snippet for how to resize array, if we don't know how many characters are going to be entered.

    /*read in characters
    from standard input and assign them to a buffer. The buffer will contain all of the
    characters read in except for a terminating return character
    */
    #include <stdio.h>
    #include <stdlib.h>

    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);//what is the purpose of this??
                        buffer = newBuffer;
                    } 
                *currentPosition++ = character;
        }//while

        *currentPosition = '\0';
        return buffer;
    }

    int main(void)
    {
        char *s = getLine();
        printf("%s\n", s);
        return 0;
    }

I commented this part of the code

currentPosition = newBuffer + (currentPosition - buffer);

and ran the code. It still worked. I am not sure, what purpose that line of code is for, becuase the evaluation for newBuffer and buffer will always cancel each other.

Is something missing from my understanding?

If not should I follow this book religiously?

Upvotes: 2

Views: 65

Answers (1)

Grady Player
Grady Player

Reputation: 14549

currentPosition = newBuffer + (currentPosition - buffer);

so (currentPosition - buffer) is the offset (position - starting = offset)

after a realloc, the old pointer may or may not be good, it is UB... so you always need to use the new returned pointer... but the contents are copied. so it is like a new bigger buffer and you need to update your current position to the same offset in the new buffer ... so

currentPosition = newBuffer + (currentPosition - buffer);

makes perfect sense...

Upvotes: 2

Related Questions