malloc - Will free() work on a second pointer to an array in C? -


let's have code set this:

#include <stdlib.h> #include <stdio.h>  int main() {     char* primary = malloc(10);    // main pointer heap memory     char* secondary = primary;     // alias main pointer     free(secondary); } 

will free(secondary) release memory assigned primary?

yes, free() work on pointer holds address in turn returned of malloc(), calloc() or realloc(). although doing little bit dangerous since risk free()ing pointer twice. 1 of 2 shall passed free() , after cannot again either of them.

it's common practice set pointer null right after passing free() avoid having dangling poitner , avoid freeing pointer more once "accidentally", in scenario describe risk setting 1 of pointers null.

in short, if primary become dangling pointer twice dangerous having secondary dangling pointer.


Comments