C-Allocators: Mention cleanup
attribute
Signed-off-by: Daiki Ueno <dueno@redhat.com>
This commit is contained in:
parent
e6baf3d2fb
commit
c253c7d93e
1 changed files with 24 additions and 0 deletions
|
@ -105,6 +105,30 @@ Otherwise, call `malloc`. When exiting the
|
||||||
function, check if `malloc` had been called,
|
function, check if `malloc` had been called,
|
||||||
and free the buffer as needed.
|
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]]
|
[[sect-Defensive_Coding-C-Allocators-Arrays]]
|
||||||
=== Array Allocation
|
=== Array Allocation
|
||||||
|
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue