Jack
Jack

Reputation: 16724

realloc() are not returning a new block with a copy of old values

Consider this code:

char buffer[] = "abcdefghijklmnopqrstuvwxyz",
*val = malloc(10), *pbuf = buffer, *pval = val, *tmpbuf;

int size = 10,loaded = 0;

while(*pbuf) {

    if((loaded + 1) >= size) {
        size += 10;
        tmpbuf = realloc(val, size);

        if(tmpbuf != NULL) {
            val = tmpbuf;
            pval = val;
        } else {
            printf("realloc()\n");
            exit(-1);
        }
    }

    *pval ++= *pbuf ++;
    loaded ++;
}

*pval ++= '\0';
printf("%s\n", val);
free(val);

it print tuvwxyz instead of abcdefghijklmnopqrstuvwxyz.

Why? the new pointer returned by realloc() is not preserving the previously buffer passed, according to the documentation.

Upvotes: 3

Views: 443

Answers (2)

fbafelipe
fbafelipe

Reputation: 4952

It is copying the buffer to the new buffer (if not the same). The problem is that you are overwriting the buffer. "pval = val;" set your writing point to the first byte of the buffer, reaplacing any content. Try changing to "pval = val + loaded;".

Upvotes: 4

Hugh
Hugh

Reputation: 8932

After the call to realloc, you reassign pval to val, which is in turn assigned from tmpbuf. In other words, after each call to realloc, pval is reset point to the beginning of your dynamic buffer.

Upvotes: 2

Related Questions