Why is it safe to return string2? At the end of the function, the stack frame would not be overwritten? I've seen many compilers store the literal "hello" in a read-only area of memory, is that why it's safe to return string2 without the stack frame being overwritten?
A greeting and thanks in advance
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *imprimir_cadena( char *cadena2 ) {
return cadena2;
}
int main( ){
char *ptr = "hola";
char *p = imprimir_cadena( ptr );
printf( "%s", p );
return 0;
}
The return you make is safe, regardless of whether the literal is stored in a read-only zone or not.
To understand why it is safe, look at this other case:
Does this code seem dangerous to you? Obviously not, because you are returning a copy of the
valor
one you received as a parameter. Although the variablevalor
exists on the stack and only while the function is executing, itreturn
evaluates the expressionvalor
, and returns the result of that expression.The same is true when the expression is a pointer. What it returns is the value of the pointer, that is, the address it points to (which is the same address it pointed to
ptr
in your example, which is off the stack of that function).In your code both of
p
themptr
point to the same memory address, that is, to the address of the constant"hola"
, which is safe, it's safe, since you only pass it as an argument to the function, which doesn't prevent its address from changing. Now, if you do:Some compilers will complain that you are returning a local variable, others won't (And the ones that allow returning optimize the memory address of
cad
) , the important thing here is that with the method I put above you invoke undefined behavior, but in the way that you pose, it is perfectly safe to return the same pointer that was received as an argument.cadena2
It is a pointer yes, and it is also local... but the memory it points to is notcadena2
local, so nothing will happen to the memory pointed to by once the program leaves the function. Another thing would happen if we use memory belonging to the function itself:The program will also compile but we still don't get the expected result...
It is safe because the region of memory it points to remains valid after the program exits the function.
For the code that I have given you before to work correctly, it would suffice, for example, to declare the variable
cadena2
as static:This way the variable
cadena2
does not die with the function. Another possibility would be to use dynamic memory:The only requirement we have to meet, therefore, is that the memory region returned by the pointer be valid outside of the function.