Why is realloc only copying part of the data? [closed]
Why is realloc only copying part of the data? [closed]
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!
This question appears to be off-topic. The users who voted to close gave these specific reasons:
1 Answer
1
You are reallocating to 4
bytes, not to 4*sizeof(int)
, which incidentally copies just first int
(and discards other).
4
4*sizeof(int)
int
realloc
, as malloc
, works on bytes so you must use them both in the same way.
realloc
malloc