Search code examples
cmemory-managementrealloc

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.


Solution

  • 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;".