-1

i m new to C Language

this is my code:

char* getString()
{
char s[] = "Will I be printed?"; 
return s;
}
int main()
{
printf("%s", getString());
getchar();
}

it showing warning that : function returns address of local variable

now when i code this :

char* getString()
{
char *s = "Will I be printed?"; 
return s;
}
int main()
{
printf("%s", getString());
getchar();
}

it will print the string : "Will I be printed?"

why is that? is it trur that both pointer and character array is LOCAL Variable and they stored in Stack..?

P.S i am using http://ide.geeksforgeeks.org/

2 Answers2

2

In both cases, it is likely that the string literal itself is stored in a read-only data area in the object file, which is mapped into the program's address space.

In the first case, storage for the string will be allocated on the stack, and the compiler will probably generate some code to make a copy of the string, stored on the stack. When the function returns, that storage is reclaimed, and attempting to access it from outside the function, via a returned pointer into the stack, is undefined behavior, and you get a compiler warning.

In the second case, the address of the string literal is stored in the char * variable. It will point directly to wherever the string literal is stored in the runtime address space. When the function returns the pointer value (note: not the address of the pointer itself, which is on the stack, but the value it holds, which is a pointer into the string storage area), the address remains valid outside the scope of the function, and the program works as expected.

Jim Lewis
  • 43,505
  • 7
  • 82
  • 96
  • thanks @Jim Lewis ..Got IT!! It means that String literal in second case Stored in a **Runtime Address Space and not in Stack Segment** :) – chirag chevli Oct 11 '17 at 17:52
0

First, don't mark this C++, it's not c++.

It throws the warning because the array you created in the first form of your function is a local variable and will be destroyed once you're outside the scope. You're returning a memory address to something that gets deleted essentially.

The second function works because you're creating a pointer that points to the string which isn't defined locally, it's just a spot in memory that you can then use.

Kilbo
  • 333
  • 1
  • 12