c - Two pointers are pointing to same memory address, how to avoid memory leak in case freeing of these two happens at independence place? -


int *a = malloc(40); int *b; b=a; if( *some conditions* ) free(a); // know 'a' has been allocated chunk of memory x times // , free(a) has been called less x times. 

i have no idea of condition, don't know whether 'a' has been freed or not! how sure if 'b' i.e. 'a' has been freed or not.

if want make sure subsequent calls of free on pointer dynamically allocated memory not harm, should assign null pointer. because (emphasis added):

the free() function frees memory space pointed ptr, must have been returned previous call malloc(), calloc() or realloc(). otherwise, or if free(ptr) has been called before, undefined behavior occurs. if ptr null, no operation performed.

if want make sure pointer b refer same object other pointer a points at, turn b pointer a instead (and dereference each time need use it):

#include <stdio.h> #include <stdlib.h>  int main() {     /* dynamically allocate memory */     int *a = malloc(40);     /* b pointer pointer int */     int **b;     /* make b point */     b = &a;     if ( 1 ) {         /* free memory , assign null pointer */         free(a);         = null;     }     /* nothing bad happen when dereference b */     printf("%p\n", *b);     /* nothing bad happen when free memory region        pointer b points points */     free(*b); } 

another thing on memory leaks. there no memory leaked when double-free memory. in case stumble undefined behavior, in case anything happen. because shall not access memory regions not own (anymore) (c.f., great post). instead, leak memory when loose reference block of dynamically allocated memory. example:

/* allocate memory */ int *a = malloc(40); /* reassign without free-ing memory before : have leaked memory */ = malloc(40); 

Comments

Popular posts from this blog

linux - xterm copying to CLIPBOARD using copy-selection causes automatic updating of CLIPBOARD upon mouse selection -

c++ - qgraphicsview horizontal scrolling always has a vertical delta -