I have two pointers:
double *a, *b;
a = (double *) malloc (N*sizeof (double));
b = (double *) malloc (N*sizeof (double));
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
free(a) prior to reassignment fixes this problem. Once you assign
a=b, you need to be careful with using
a after calling
a becomes a dangling pointer.
Is it different if
ais global and
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.