Returning string from a C function [duplicate]

2019-08-01 16:35发布

This question already has an answer here:

I have a simple code.

#define MY_STRING "String example"

char* string_return_function()
{
    return MY_STRING;
}

The above code works but I am not sure how. I think the string_return_function() returns a local address, which would gets freed once the function exits.

3条回答
不美不萌又怎样
2楼-- · 2019-08-01 17:06

String literals are allocated in static read-only memory, usually called .rodata (read-only data). They persist throughout the whole life-time of your program, so it is safe to return a pointer to one.

Had you however copied the string literal into a temporary stack variable, the code would be unsafe and invoke undefined behavior:

char* string_return_function()
{
    char mystring [] = "String example";
    return mystring; // BAD
}
查看更多
看我几分像从前
3楼-- · 2019-08-01 17:10

No, that's not how it works.

String literals are stored in memory that persists for as long as the program runs, so the function just returns a pointer to the string constant.

There is no string creation/initialization happening at run-time, no characters are copied around. It's just returning a pointer, the function's machine code is likely just a couple of instructions.

For example, here's the (cleaned-up) x86 code I got from https://assembly.ynh.io/:

string_return_function:
  movl  $.LC0, %eax
  ret

Where .LC0 is simply a location holding the string. So, that's 2 instructions including the return from functin overhead/boilerplate. Pretty efficient. :)

You're thinking of this:

char * bad_code(void)
{
  char response[] = MY_STRING;
  return response;
}

This is bad code since it returns a local array. It doesn't matter that the array in question is initialized from the literal, that's not what's being returned.

Also, don't name your function starting with str, all such names are reserved; the C11 draft says:

Function names that begin with str, mem, or wcs and a lowercase letter may be added to the declarations in the <string.h> header.

查看更多
Emotional °昔
4楼-- · 2019-08-01 17:26

String literals result in an array of char with static storage duration.

For example, the 1999 C standard, section 6.4.5, para 5 starts with

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.65) The multibyte character sequence is then used to initialize an array of static storage duration and length just sufficient to contain the sequence.

The static storage duration means that the array representing the string literal continues to exist after the function string_return_function() returns.

查看更多
登录 后发表回答