I found code in libcurl that looks like:
const char *
curl_easy_strerror(CURLcode error)
{
switch(error) {
case CURLE_OK:
return "No error";
case CURLE_UNSUPPORTED_PROTOCOL:
return "Unsupported protocol";
.....
}
As I know, if you want to return a pointer, you need to make sure the memory which the pointer point will not be changed or released. Why is it that this libcurl code works?
Those string literals are placed in a static read-only section of the executable at compile time. They are separate from the heap or the stack. The function is simply returning a pointer that points to those strings.
The implementation of this is platform and compiler specific, but the C11 standard has a few relevant requirements on this in section 6.4.5.
In translation phase 7, a byte or code of value zero is appended to each multibyte character sequence that results from a string literal or literals. The multibyte character sequence is then used to initialize an array of static storage duration and length just sufficient to contain the sequence.
So we know it must be stored in a static location at compile time.
If the program attempts to modify such an array, the behavior is undefined.
This tells us the data must be read-only.
Some people are complaining that this is incorrect, citing specific platforms or architectures. As noted above this is platform and compiler specific.
Some platforms, may not support read-only data, but the compiler will almost certainly try to prevent you from modifying it. Since the behavior is undefined, the intent is that you never do this, so for all intents and purposes the data is read-only.
In the context of the question, this answer is correct.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With