Skip to content

Instantly share code, notes, and snippets.

@maxux
Created June 21, 2019 02:46
Show Gist options
  • Save maxux/3a5a6907297be3f1298a84b948152e5f to your computer and use it in GitHub Desktop.
Save maxux/3a5a6907297be3f1298a84b948152e5f to your computer and use it in GitHub Desktop.
GCC / Clang Cleanup
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define discard __attribute__((cleanup(__cleanup_free)))
void __cleanup_free(void *p) {
free(* (void **) p);
}
void hello() {
discard char *freeme = NULL;
if(!(freeme = malloc(42)))
exit(EXIT_FAILURE);
strcpy(freeme, "blabla");
printf(">> %s\n", freeme);
}
int main(void) {
hello();
}
maxux@laptix /tmp $ valgrind ./freeme
==26740== Memcheck, a memory error detector
==26740== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==26740== Using Valgrind-3.15.0 and LibVEX; rerun with -h for copyright info
==26740== Command: ./freeme
==26740==
>> blabla
==26740==
==26740== HEAP SUMMARY:
==26740== in use at exit: 0 bytes in 0 blocks
==26740== total heap usage: 2 allocs, 2 frees, 1,066 bytes allocated
==26740==
==26740== All heap blocks were freed -- no leaks are possible
==26740==
==26740== For lists of detected and suppressed errors, rerun with: -s
==26740== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
@delandtj
Copy link

c'est cool cet arrtibute

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment