user2178841 user2178841 - 1 year ago 77
C Question

allocated memory after reasignment of pointer

I have two pointers:


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
. and assign values.

then if I do,


points to array
was pointing to.

What happens to memory allocated to a? Is following better alternative:


or only


or a=b;

or is it illegal?

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

Answer Source
  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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download