free_null.c
#include <stdlib.h> // free()
#include <stdbool.h> // bool, true, false
bool free_null(void **ptr)
{
if (ptr && *ptr) {
free(*ptr);
*ptr = NULL;
return true;
}
return false;
}
コメントで書いていただいたマクロ
free_null_macro.c
#include <stdlib.h> // free()
#define FreeNull(ptr) do {free(ptr); ptr = NULL;} while (0)
ダブルポインタ版
free_null_dptr.c
#include <stdlib.h> // free()
#include <stdbool.h> // bool, true, false
bool free_null_dptr(void ***ptr)
{
if (ptr && *ptr) {
void **current = *ptr;
while (*current) {
free(*current);
*current = NULL;
current++;
}
free(*ptr);
*ptr = NULL;
return true;
}
return false;
}
別パターン
free_null_dptr.c
#include <stdlib.h> // free()
#include <stdbool.h> // bool, true, false
bool free_null_dptr(void ***ptr)
{
if (ptr && *ptr) {
size_t i = 0;
while ((*ptr)[i]) {
free((*ptr)[i]);
(*ptr)[i] = NULL;
i++;
}
free(*ptr);
*ptr = NULL;
return true;
}
return false;
}
シングルポインタ用 free_null()
とダブルポインタ用 free_null_dptr()
を合わせたもの
free_null.c
#include <stdlib.h> // free()
#include <stdbool.h> // bool, true, false
bool free_null(void **ptr)
{
if (ptr && *ptr) {
free(*ptr);
*ptr = NULL;
return true;
}
return false;
}
bool free_null_dptr(void ***ptr)
{
if (ptr && *ptr) {
void **current = *ptr;
while (*current) {
free_null(current); // = free_null(&*current);
current++;
}
free(*ptr);
*ptr = NULL;
return true;
}
return false;
}
別パターン
free_null.c
bool free_null_dptr(void ***ptr)
{
if (ptr && *ptr) {
size_t i = 0;
while ((*ptr)[i]) {
free_null(&((*ptr)[i]));
i++;
}
free(*ptr);
*ptr = NULL;
return true;
}
return false;
}