Why is realloc only copying part of the data?

3790 views c
3

So I ran into an issue where it seemed like realloc wasn't copying all of the data in a buffer so I decided to run the following code as a test.

#include <stdlib.h>

int main(int argc, char** argv)
{
    int* tmp_array = malloc(sizeof(int) * 2);
    tmp_array[0] = 1;
    tmp_array[1] = 2;
    tmp_array = realloc(tmp_array, 4);

    return 0;
}

The same issue I originally had was still happening, only part of the data is being copied. The 1 in the buffer gets copied, however the 2 does not. I am allocating enough space for 2 integers at first so both if the assignments to tmp_array should be valid. Then reallocating to 4 seems valid. I even tried explicitly casting the returned realloc pointer to int* but that didn't help.

Unfortunately, I can't show the screenshots of my memory window in the debugger (VS 2017) but it definitely shows the 1 and 2 in the buffer before realloc and only shows the 1 in the buffer after the realloc.

I'm sure I could reimplement realloc myself by just using malloc and memcpy to copy the data over manually, but I still just want to know why this isn't working.

Any help is greatly appreciated!

answered question

2 Answers

3

You are reallocating to 4 bytes, not to 4*sizeof(int), which incidentally copies just first int (and discards other).

realloc, as malloc, works on bytes so you must use them both in the same way.

posted this
1

Replace this

tmp_array = realloc(tmp_array, 4); /* it copies only 4 bytes */

as

tmp_array = realloc(tmp_array, ele*sizeof(int)); /* ele -> for how many ints you want to reallocate */

as second argument of realloc() is the total new size in bytes. For e.g if you want to re-allocate for 2 integers, you should use 2*sizeof(int).

posted this

Have an answer?

JD

Please login first before posting an answer.