On this page
Error Handling & goto cleanup
Prev: Memory Layout, Alignment & Qualifiers | Up: compilation_and_internals | Next: tutorials
Rel: Error-Handling Philosophies, stdio.h & File I/O
Ref: cppreference — errno
Tags: #public #prog #c #internals #errors
Contents
Single-Exit goto cleanup Pattern
Because C has no exceptions or destructors, the idiomatic way to prevent leaks across multi-resource functions is initializing every resource handle to NULL and jumping to a single cleanup: label on error:
#include <stdio.h>
#include <stdlib.h>
int process_file(const char *path) {
int rc = -1;
FILE *fp = NULL;
char *buf = NULL;
fp = fopen(path, "rb");
if (!fp) goto cleanup;
buf = malloc(4096);
if (!buf) goto cleanup;
/* ... work with fp and buf ... */
rc = 0;
cleanup:
free(buf);
if (fp) fclose(fp);
return rc;
}
Return Codes & errno
Return 0 on success and negative error codes (or a typed enum Status) on failure; inspect errno only immediately after a standard library call reports failure.
Linked from
- tuts/c/compilation_and_internals
- tuts/c/compilation_and_internals/error_handling_and_cleanup
- tuts/c/compilation_and_internals/memory_layout_and_abi
- tuts/c/stdlib/errno
- tuts/c/stdlib/errno/errno
- tuts/c/stdlib/math_time_and_assert
- tuts/c/stdlib/setjmp
- tuts/c/stdlib/setjmp/setjmp
- tuts/c/stdlib/signal
- tuts/c/stdlib/signal/signal
- tuts/c/stdlib/stdio_and_file_io
Related notes
- tuts/c/compilation_and_internals Linked here; links to this page; shared tags: #c, #internals, #prog
- tuts/c/compilation_and_internals/memory_layout_and_abi Linked here; links to this page; shared tags: #c, #internals, #prog
- tuts/c/stdlib/stdio_and_file_io Linked here; links to this page; shared tags: #c, #prog
- tuts/c/stdlib/errno links to this page; shared tags: #c, #prog
- tuts/c/stdlib/errno/errno links to this page; shared tags: #c, #prog
- tuts/c/stdlib/math_time_and_assert links to this page; shared tags: #c, #prog
- tuts/c/stdlib/setjmp links to this page; shared tags: #c, #prog
- tuts/c/stdlib/setjmp/setjmp links to this page; shared tags: #c, #prog
- tuts/c/stdlib/signal links to this page; shared tags: #c, #prog
- tuts/c/stdlib/signal/signal links to this page; shared tags: #c, #prog