Module <cweb/autofree.h> — automatic cleanup (GCC/Clang)
Supports deterministic cleanup when variables leave scope — via the non-standard but common GCC/Clang cleanup attribute.
Macros
| Macro | Cleanup target |
|---|---|
AUTOFREE |
free(*) for pointers |
AUTOFREE_CLOSE_FILE |
fclose for FILE* |
AUTOFREE_CLOSE_DIR |
closedir for DIR* |
AUTOFREE_CLOSE_SOCKET |
close socket |
AUTOFREE_PTRPTR |
double-pointer release via cweb_cleanup_free_ptrptr |
Example:
void example(void) {
AUTOFREE char *buf = malloc(128);
(void)snprintf(buf, 128, "ok");
/* buf is automatically freed at end of block */
}
Cleanup functions
These functions are not called directly; the compiler inserts them when the corresponding AUTOFREE* macros are used. Direct use may be needed for custom __attribute__((cleanup(...))) wrappers.
void cweb_cleanup_free(void *p)
- Purpose:
free(*(void**)p)— typical forchar *,void *.
void cweb_cleanup_close_file(FILE **fp)
- Purpose: Closes an open
FILE*when the pointer is non-null.
void cweb_cleanup_close_socket(int *sockfd)
- Purpose: Closes a socket file descriptor.
void cweb_cleanup_close_dir(DIR **dp)
- Purpose: Closes a directory handle.
void cweb_cleanup_free_ptrptr(void **p)
- Purpose: Frees a pointer referenced via a double pointer.
Notes
- Only meaningful with GCC or Clang; MSVC does not support this pattern natively.
- Semantics match local
gotocleanups — onreturn,break,continue, scope exit runs.