user13709754
user13709754

Reputation:

Do I need to free the result of strerror() in C?

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?

Upvotes: 5

Views: 1684

Answers (2)

R.. GitHub STOP HELPING ICE
R.. GitHub STOP HELPING ICE

Reputation: 215407

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 mmapped translation file, and it's likely that the error would immediately be caught as a crash.

Upvotes: 9

dbush
dbush

Reputation: 224387

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.

Upvotes: 2

Related Questions