Why is it safe to return string2? at the end of the function the stack frame would not be overwritten?
cadena2
is a pointer yes, and it is also local ... but the memory pointed to by no is local, then the memory pointed to by cadena2
is not going to happen nothing once the program leaves the function. Something else would happen if we use memory belonging to the function itself:
char* func2()
{
char cadena2[] = "hola";
return cadena2; // <<--- cuidado!!!
}
int main()
{
char* ptr = func2();
puts(ptr);
return 0;
}
The program will also compile but we do not get the expected result ...
I've seen many compilers save the literal "hello" in a memory-only zone, which is why it's safe to return string2 without the stack frame being overwritten?
It's safe because the region of memory it points to remains valid after the program leaves the function.
For the code that I have put you before to work properly, it would be enough, for example, to declare the variable cadena2
as static:
char* func2()
{
static char cadena2[] = "hola";
return cadena2;
}
In this way the variable cadena2
does not die with the function. Another possibility would be to use dynamic memory:
char* func2()
{
char* cadena2 = (char*)malloc(5*sizeof(char));
strcpy(cadena2,"hola");
return cadena2;
}
int main()
{
char* ptr = func2();
puts(ptr);
free(ptr); // No olvidemos liberar la memoria
return 0;
}
The only requirement that we have to fulfill, therefore, is that the region of memory returned by the pointer is valid outside the function.