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

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

Edmonton

Crossroads (UK TV series)