To my understanding, strerror(errno)
returns the string form of the error corresponding to errno
. In that case, do I need to free the returned result of the function once I finished using it?
-
1No. See https://en.cppreference.com/w/c/string/byte/strerror – paddy Jun 08 '20 at 23:38
-
It's a good question because strerror() returns "char*" and not "const char*". That's strange. – zomega Apr 22 '22 at 06:58
2 Answers
Not only do you not need to; you must not. The only things you can pass to free
are pointers to memory you obtained by malloc
or a function specified to return memory obtain by malloc
or "as if by malloc
". There is no such text in the specification of strerror
, so passing the string it returns to free
would produce undefined behavior. In particular, if the implementation uses malloc
internally to obtain the memory, you would be freeing that memory out from under it, causing it to perform use-after-free or double-free, which are some of the most dangerous types of memory bugs.
In practice, strerror
usually returns immutable strings from libc .rodata
or from a mmap
ped translation file, and it's likely that the error would immediately be caught as a crash.

- 208,859
- 35
- 376
- 711
-
strerror() returns "char*" and not "const char*". So when you say the string is immutable that can't be right. – zomega Apr 22 '22 at 06:58
-
@somega: The qualification of the pointed-to type for a pointer has nothing to do with whether what it points to can be modified. `char *` can point to `const char` or to (an element of) a `char []` array that is not modifiable (e.g. because it's a string literal). Whether you're permitted to modify something is a matter of the language specification and interface contract of the function that gave you the pointer, not the type. – R.. GitHub STOP HELPING ICE Apr 22 '22 at 14:07
-
Do you have an explanation why it is defined as "char*" and not as "const char*"? – zomega Apr 22 '22 at 14:20
-
@somega: Because lots of C code is not const-correct and would produce warnings (should be errors) due to things like `char *msg = strerror(errno);` Historically C did not even have the `const` keyword, and `strerror` likely even predates the addition of `const`. It's a normal idiom for functions to return non-const-qualified pointers like this, and necessary for some like `strchr` where whether the object is modifiable depends on what you passed in. – R.. GitHub STOP HELPING ICE Apr 22 '22 at 14:23
The return value of strerror
does not need to be free'ed. It typically points to a read-only string or a static buffer. Because of this, this function is not considered thread safe.
There is a related function called strerror_r
, which takes a user specified buffer and its size and fills the buffer with the error message. This function is thread safe.

- 205,898
- 23
- 218
- 273