Writing C code and handling errors effectively is crucial for developing robust applications. Some tips to help you with both:
Check Return Values:
FILE *file = fopen("example.txt", "r");
if (file == NULL) {
perror("Error opening file");
return 1;
}
Use errno
:
errno
is set by system calls and some library functions to indicate the error type. Use it with the perror()
function or strerror()
to get a human-readable error message.if (some_function() == -1) {
perror("some_function failed");
}
Handle Memory Allocation Failures:
malloc()
or calloc()
, always check if the returned pointer is NULL
to handle memory allocation failures.int *arr = malloc(sizeof(int) * size);
if (arr == NULL) {
fprintf(stderr, "Memory allocation failed\\\\n");
return 1;
}
Validate Input:
if (input < 0 || input > MAX_VALUE) {
fprintf(stderr, "Input out of range\\\\n");
return 1;
}
Use Assertions for Debugging:
assert()
to check assumptions and invariants in your code during development. This helps catch bugs early.#include <assert.h>
void process(int *data) {
assert(data != NULL);
// Process data
}