0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

free_null()

Last updated at Posted at 2024-12-02
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;
}
0
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?