Reputation: 47
This is a function used to reallocate some memory on a dynamic array. I have typedef'd struct lottery
to lot
. I am passing by reference the array of structures (a
) and the new size I want it to have (n
). I am declaring a temporary array (b
) so I can realloc to a
.
My question is: I am creating some bytes on the heap with b = realloc()
etc., but if I free(b)
before I quit the function it doesn't work properly. If I call it again b == NULL
becomes true
, but if I remove the free(b)
it works just fine, but I think that is not right thing because I am leaving garbage bytes on the heap. Can someone please explain to me the problem?
lot *Enterd(lot **a, int n) {
lot *b = NULL;
b = (lot *)realloc(*a, n * sizeof(lot));
if (b == NULL) {
printf("Memory could not be allocated for the new input.\n");
return NULL;
}
*a = b;
free(b);
return *a;
}
Upvotes: 0
Views: 52
Reputation: 85827
b = realloc(*a, X)
frees the memory associated with *a
and allocates a new allocation of size X
, stored in b
.
Now when you do *a = b
, both *a
and b
reference this new allocation.
After free(b)
, that allocation is released and both b
and *a
become invalid pointers. At that point return *a
has undefined behavior.
If you don't free b
, all is fine. You don't leak memory because you still have a pointer to it: Both via *a
(which references a variable in the caller) and the function's return value.
(Also, don't cast realloc()
.)
Upvotes: 1