Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does a function returning const char * with string literals work? [duplicate]

Tags:

c

malloc

libcurl

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?

like image 813
NewBee Avatar asked May 17 '19 03:05

NewBee


Video Answer


1 Answers

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.

Reference

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.

Edit

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.

like image 70
cj.vaughter Avatar answered Oct 21 '22 01:10

cj.vaughter