char *myfunc() {
char *temp = "string";
return temp;
}
In this piece of code, where does the allocation of the object pointed to by temp happen and what would be its scope?
Is this function a valid way to return a char* pointer?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Is the code correct?
Yes your code is (almost) fine, because
"string"is a string literal and located in static storage.Note: A pointer is just a variable which stores a memory address. This line simply stores the address of the string literal “string” inside a variable called
temp.The C++ standard guarantees that the string literal will stay in memory for the duration of the program as defined below. Which means you are free to use that memory address in any scope anywhere during the whole life of your program.
Why?
The C++03 standard (current) has this to say:
And section 3.7.1 – 1:
Warning:
In your code you are returning a
char*, you should really be returning aconst char *. It is undefined behavior if you try to modify a string literal, and your function return value shouldn’t pretend to allow it.On a related side note to the warning. If you have in your code in 2 different places a string called
"string"then whether or not they are distinct strings is implementation defined.