If I have a pointer pointing to another pointer (both created with the function Malloc()). How can I free the memory? | SoloLearn: Learn to code for FREE!

+1

If I have a pointer pointing to another pointer (both created with the function Malloc()). How can I free the memory?

2/4/2020 6:41:45 AM

Carlos Caminero

2 Answers

New Answer

+8

It is unnecessary to allocate memory for a pointer that will just point to another allocated memory pointer, but IDK the code so I wont bother. Generally, it is a good idea to free memory in the reverse order they were allocated. We deallocate with the free function in C. int *p1 = malloc(sizeof(int) * 4); int *p2 = malloc(sizeof(int) * 3); free(p2); p2 = NULL; free(p1); p1 = NULL;

+1

just like 「HAPPY TO HELP」 to help you don't have to "it's unnecessary to allocate memory for a pointer that will just point to another allocated memory pointer" but you can still do this int *ptr1 = malloc(sizeof(int) *3); int *ptr2 = ptr1; then you can free ptr1 from ptr2 since they both point to the same address free(ptr2); ptr2=NULL;