
SC22/WG14 (C Standards) Committee Convener. Standards Lead @Woven_Toyota. Author of Effective C and Secure Coding in C and C++. Slayer of trigraphs.
- Tweets13.9K
- Following1.7K
- Followers4.7K
- Likes242K
![Example cleanup code using POSIX's open/close functions for file descirptors:
#include <fcntl.h>
#include <unistd.h>
void closep(void* ptr) {
int* p = ptr;
if (!p || *p == -1) return;
close(*p);
}
#define return_fd(desc) return ({ auto t = desc; desc = -1; t; })
int f () {
[[gnu::cleanup(closep)]]
int fd = open("", 0, 0);
if (fd < 0)
return -1; // Safe since closep checks for < 0
bool failure = false;
// ...
if (failure)
return -1;
// ...
return_fd(fd); // Again safe
}
int main () {
return 0;
}](https://pbs.twimg.com/media/HQ05lL5XUAAH4OA.jpg?name=small&format=webp)
ALT Example cleanup code using POSIX's open/close functions for file descirptors: #include <fcntl.h> #include <unistd.h> void closep(void* ptr) { int* p = ptr; if (!p || *p == -1) return; close(*p); } #define return_fd(desc) return ({ auto t = desc; desc = -1; t; }) int f () { [[gnu::cleanup(closep)]] int fd = open("", 0, 0); if (fd < 0) return -1; // Safe since closep checks for < 0 bool failure = false; // ... if (failure) return -1; // ... return_fd(fd); // Again safe } int main () { return 0; }

ALT #include <fcntl.h> #include <unistd.h> #define return_fd(desc) return ({ auto t = desc; desc = -1; t; }) int f () { int fd = open("", 0, 0); if (fd < 0) return -1; // Safe since closep checks for < 0 #if STYLE_1 _Defer { if (fd != -1) { close(fd); } } #else _Defer if (fd != -1) close(fd); #endif bool failure = false; // ... if (failure) return -1; // ... return_fd(fd); // Again safe } int main () { return 0; }


















