-
realloc question
I've been playing with pointers and dynamic memory allocation for the last couple of days. Did I get the code below right? I want ptr1 and ptr2 to point to the same memory location. I suppose the address of the memory "block" might change after the call to realloc, so I put the address in ptr1 to ptr2 again. Is that correct?
Code:
int *ptr1, *ptr2;
ptr1 = (int *)malloc(sizeof(int));
ptr2 = ptr1;
/* some code here*/
ptr1 = realloc(ptr1, 3);
ptr2 = ptr1; // Necessary?
-
Yes it's necessary after realloc()... as you correctly discerned, the address can/will change.
Also beware of your malloc() calls... sizeof(int) will allocate only 4 bytes (the size of an integer variable) or as few as 2 bytes if you are in India.
-