From c253c7d93ea65646a1d674fee9633174a3be734b Mon Sep 17 00:00:00 2001 From: Daiki Ueno Date: Mon, 12 Oct 2020 10:21:28 +0200 Subject: [PATCH] C-Allocators: Mention `cleanup` attribute Signed-off-by: Daiki Ueno --- .../programming-languages/C-Allocators.adoc | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/modules/ROOT/pages/programming-languages/C-Allocators.adoc b/modules/ROOT/pages/programming-languages/C-Allocators.adoc index 6bb137a..8c858f6 100644 --- a/modules/ROOT/pages/programming-languages/C-Allocators.adoc +++ b/modules/ROOT/pages/programming-languages/C-Allocators.adoc @@ -105,6 +105,30 @@ Otherwise, call `malloc`. When exiting the function, check if `malloc` had been called, and free the buffer as needed. +If portability is not important in your program, an alternative way of +automatic memory management is to leverage the `cleanup` attribute +supported by the recent versions of GCC and Clang. If a local variable +is declared with the attribute, the specified cleanup function will be +called when the variable goes out of scope. + +[source,c] +---- +static inline void freep(void *p) { + free(*(void**) p); +} + +void somefunction(const char *param) { + if (strcmp(param, "do_something_complex") == 0) { + __attribute__((cleanup(freep))) char *ptr = NULL; + + /* Allocate a temporary buffer */ + ptr = malloc(size); + + /* Do something on it, but do not need to manually call free() */ + } +} +---- + [[sect-Defensive_Coding-C-Allocators-Arrays]] === Array Allocation