Skip to content

Instantly share code, notes, and snippets.

@mts0629
Created March 13, 2022 15:22
Show Gist options
  • Save mts0629/0439d1bc33745a028ddba37daeb75195 to your computer and use it in GitHub Desktop.
Save mts0629/0439d1bc33745a028ddba37daeb75195 to your computer and use it in GitHub Desktop.
free with NULL clear to avoid double-free
#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