Skip to content

Instantly share code, notes, and snippets.

@mmaxs
Last active May 25, 2020 10:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mmaxs/ea9e929cec5c6cca3ebed2c5e76da7b1 to your computer and use it in GitHub Desktop.
Save mmaxs/ea9e929cec5c6cca3ebed2c5e76da7b1 to your computer and use it in GitHub Desktop.
__attribbute__(( cleanup(...) )) quirk
/* gcc -std=c11 -Wall -Wpedantic -pedantic-errors -D_DEFAULT_SOURCE cleanup-test.c -o cleanup-test */
#include <stdlib.h>
#include <stdio.h>
struct Obj { int x; };
void Obj_cleanup(struct Obj **obj_ref)
{
fprintf(stdout, "%s() for %p\n", __func__, (void*)(*obj_ref));
fflush(stdout);
free(*obj_ref);
}
int main(void)
{
{
struct Obj *test __attribute__(( cleanup(Obj_cleanup) )) = calloc(1, sizeof(struct Obj));
fprintf(stdout, "Obj allocated at %p\n", (void*)test);
fprintf(stdout, "Quitting the test scope...\n");
goto main__sub1;
main__exit:
return 0;
} // <-- Obj_cleanup is executed here twice, even though the control flow passes the 'test' definition only once
main__sub1:
fprintf(stdout, "The test scope has been quit.\n");
goto main__exit;
}
@mmaxs
Copy link
Author

mmaxs commented May 24, 2020

Output is:

Obj allocated at 00000000005F6880
Quitting the test scope...
Obj_cleanup() for 00000000005F6880
The test scope has been quit.
Obj_cleanup() for 00000000005F6880

https://godbolt.org/z/D9gfSb

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