C-Menu 0.2.9
A User Interface Toolkit
Loading...
Searching...
No Matches
safe_strerror.h
Go to the documentation of this file.
1#ifndef SAFE_STRERROR_H
2#define SAFE_STRERROR_H
3
4// 1. Force feature test macros before any standard headers are pulled in
5#if defined(__linux__) || defined(__gnu_linux__)
6#ifndef _GNU_SOURCE
7#define _GNU_SOURCE 1
8#endif
9#endif
10
11#include <errno.h>
12#include <stddef.h>
13#include <string.h>
14
15/**
16 * @brief Thread-safe cross-platform error string retriever.
17 * @param errnum The errno code (e.g., errno).
18 * @param buf User-provided destination character buffer.
19 * @param buflen Size of the provided buffer.
20 * @return char* Pointer to the error string (either 'buf' or an internal static string).
21 */
22static inline char *safe_strerror(int errnum, char *buf, size_t buflen) {
23 if (buf == nullptr || buflen == 0) {
24 return "Invalid buffer provided";
25 }
26
27#if defined(_WIN32) || defined(_WIN64)
28 // Windows implementation using bounds-checked standard function
29 if (strerror_s(buf, buflen, errnum) == 0) {
30 return buf;
31 }
32 return "Unknown Windows error";
33
34#elif defined(__APPLE__) || defined(__FreeBSD__) || defined(__OpenBSD__) || (defined(_POSIX_C_SOURCE) && !defined(_GNU_SOURCE))
35 // POSIX-compliant version (returns int) used by macOS and POSIX-strict environments
36 if (strerror_r(errnum, buf, buflen) == 0) {
37 return buf;
38 }
39 return "Unknown POSIX error";
40
41#elif defined(__linux__) || defined(__gnu_linux__)
42 // GNU-specific strerror_r (returns a char*, which might NOT be the buffer you passed)
43 return strerror_r(errnum, buf, buflen);
44
45#else
46 // Fallback if no thread-safe alternative is safely exposed
47 // Note: plain strerror is not thread-safe, but acts as a last resort
48 (void)buf;
49 (void)buflen;
50 return strerror(errnum);
51#endif
52}
53
54#endif // SAFE_STRERROR_H
#define _GNU_SOURCE
Definition amort.c:9