Question
Is there any way to get the maximum size of any string correlated with errno
at compile time (at preprocessor time would be even better)? E.g. an upper bound on strlen(strerror(errno))
?
My Thoughts
The best I can think of is running a program to do a brute-force search over the range of an int, over each locale, to get the string associated with each {errno, locale} pair, get its size, and generate a header on that system, then hooking that into e.g. a makefile or autoconf or whatever. I can't think of a better way to do it, but it seems ridiculous that it would be so: the standard library for a system has that information built-in, if only implicitly. Is there really no good way to get that information?
Okay, I'll admit the C and/or C++ standards might permit for error strings generated at runtime, with e.g. specific-to-circumstance messages (e.g. strerror(EINVAL)
giving a string derived from other runtime metadata set when errno
was last set, or something) - not sure if that is allowed, and I'd actually welcome such an implementation, but I've never heard of one existing which did so, or had more than one string for a given {errno
, locale} pair.
Motivation
For context, what I specifically wanted (but I think this question is valuable in a more general way, as was discussed amongst the comments) that led to this question was to be able to use the error string associated with errno
in the syscall/function writev
. In my specific usecase, I was using strings out of argv
and errno
-linked strings. This set my "worst-case" length to ARG_MAX
+ some max errno string length
+ size of a few other small strings
).
Every *nix document I've consulted seems to indicate writev
will (or "may", for what little good that difference makes in this case) error out with errno
set to EINVAL
if the sum of the iov_len
values overflows SSIZE_MAX
. Intuitively, I know every errno
string I've seen is very short, and in practice this is a non-issue. But I don't want my code mysteriously failing to print an error at all on some system if it's possible for this assumption to be false. So I wrote code to handle such a case - but at the same time, I don't want that additional code being compiled in for the platforms which generally clearly don't need it.
The combined input of the answers and comments so far is making me lean towards thinking that in my particular use-case, the "right" solution is to just truncate obscenely long messages - but this is why I asked the question how I did initially: such information would also help select a size for a buffer to strerror_r
/strerror_s
(*nix/Windows respectively), and even a negative answer (e.g. "you can't really do it") is in my view useful for others' education.
Related
This question contains answers for the strings given by strerror_r
on VxWorks, but I don't feel comfortable generalizing that to all systems.