Reputation: 859
I have two pointers:
1.
double *a, *b;
a = (double *) malloc (N*sizeof (double));
b = (double *) malloc (N*sizeof (double));
that point to huge memory space that I allocate using malloc
. and assign values.
then if I do,
a=b;
a
points to array b
was pointing to.
What happens to memory allocated to a? Is following better alternative:
free(a);
a=b;
free(b);
or only
a=b;
free(b);
or a=b; free(a);
or is it illegal?
Upvotes: 1
Views: 48
Reputation: 8527
When you do a=b
, a
points to the array being pointed to by b
. Then, the only memory you would want to free is the array initially pointed to by a
. For doing that,
free(a);
a=b;
Here, you are freeing the memory being pointer to by a
and making a
point to the memory being pointed to by b
. If you first do a=b
, you have a
pointing to the array pointed to by b
, but are left with no way to access the memory that was earlier being pointed to by a
. So, you should free a
first. Moreover, if you free b
later, all you would be left is with a
and b
both pointing to NULL.
Upvotes: 1
Reputation: 726809
In your example a=b
creates a memory leak. Block of memory previously pointed to by a
becomes impossible to free, because your program no longer has a pointer to it. This may not lead to an immediate problem, but over time your program runs out of memory, and malloc
s start returning NULL
.
Calling free(a)
prior to reassignment fixes this problem. Once you assign a=b
, you need to be careful with using a
after calling free(b)
, because a
becomes a dangling pointer.
Is it different if
a
is global andb
is local?
Scope of the pointer does not matter here. The pointer has to be considered independently of the block of memory to which the pointer is pointing. The block is allocated in dynamic memory; the pointer to the block could be anywhere - static, automatic, or dynamic.
Upvotes: 1
Reputation: 915
What you're doing causes the memory that you allocated for a
to be leaked. That means you loose the information where it is stored in memory because you overwrite the pointer with b
. If you want to assign the pointers like you do, the solution you yourself proposed
free(a);
a=b;
free(b);
would work. But keep in mind that after freeing b
, a
points to an invalid location, because you free'd the memory. So accessing a[0]
will crash the program.
Upvotes: 1