Created
March 13, 2022 15:22
-
-
Save mts0629/0439d1bc33745a028ddba37daeb75195 to your computer and use it in GitHub Desktop.
free with NULL clear to avoid double-free
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
// free and set NULL | |
// need to specify address of pointer of allocated memory block | |
void free_with_null(void **ptr) | |
{ | |
free(*ptr); | |
*ptr = NULL; | |
} | |
int main(void) | |
{ | |
int *mem = malloc(sizeof(int) * 10); | |
printf("mem=%p -> ", mem); | |
// normal free | |
free(mem); | |
printf("free -> mem=%p\n", mem); | |
mem = malloc(sizeof(int) * 10); | |
printf("mem=%p -> ", mem); | |
// free with NULL | |
free_with_null(&mem); | |
printf("free -> mem=%p\n", mem); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment