1. Brief description:
cleanup as an optional attribute value in the __attribute__ attribute
Its effect is that when the variable it declares leaves its life cycle, then
The destroy function you specify will be called automatically
2. Examples:
#include <stdio.h> #include <stdlib.h> #include <string.h> void destroy_string(char **str) { printf("final str : %s\n", *str); free(*str); } int main(int argc, char **argv) { char *str __attribute__ ((__cleanup__(destroy_string))) = NULL; str = (char*)malloc((sizeof(char)) * 100); strcpy(str, "hello world!"); printf("current str : %s\n", str); return 0; }
Results of the:
current str : hello world!
final str : hello world!
pass again
valgrind --tool=memcheck --leak-check=full Check for memory leaks
==6298== All heap blocks were freed -- no leaks are possible
You can see that the memory is correctly released
3. Principle:
In fact, the operation of releasing the code is to transfer the manual writing method to the compiler implementation.
It can be viewed by gcc -S main.c
call printf movl $0, %ebx leaq - 32 (% rbp),% rax movq % rax,% rdi call destroy_string
There is a section of this function in the main function, you will find that after calling the printf function, it will continue to call the destroy_string destroy function
But this destroy function call is not explicitly written by our code, so this is added implicitly by the compiler.