Char * stra ()
{
Char STR [] = "Hello World ";
Return STR;
}
What is the problem with this program? How can I modify it?
Resolution:The address in this STR is the first address of "Hello World" in the stack of the function. After the function call is complete, the stack frame is restored to the status before calling stra, the temporary space is reset, And the stack is "retracted". The stra stack frame is no longer within the scope of access. This program can output the results correctly, but this access method violates the function's stack frame mechanism.
However, if you call another function, you will find that this method is unreasonable and dangerous.
If you want to obtain the correct function, change it to the following:
Char * stra ()
{
Char * STR = "Hello World ";
Return STR;
}
First, we need to clarify char * STR and char STR []:
Char STR [] = "Hello World ";
Is to allocate a local array. A local array is a local variable, which corresponds to a stack in the memory. After the lifecycle of a local variable ends, the variable does not exist.
Char * STR = "Hello World ";
Is a string pointing to the constant area, located in the static storage area, it remains unchanged during the life of the program, so the string is still in. Whenever you call stra, it always returns the same read-only memory block.