user2178841 user2178841 - 3 months ago 11
C Question

allocated memory after reasignment of pointer

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?


  1. Is it different if a is global and b is local?


Answer
  1. 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 mallocs start returning NULL.

  2. 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 and b 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.

Comments