Reputation: 29
Program #1:
#include<stdio.h>
#include<stdlib.h>
char *getString()
{
char str[] = "GfG";
printf("%s \n", str);
return str;
}
int main()
{
printf("%s", getString());
return 0;
}
Output:
GfG
GfG
Program #2:
#include<stdio.h>
#include<stdlib.h>
char *getString()
{
char str[] = "GfG";
return str;
}
int main()
{
printf("%s", getString());
return 0;
}
Output:
(garbage value)
Please explain why because of only a printf
statement output differs. What is exact description?
Upvotes: 1
Views: 231
Reputation: 1796
Local variable char str[] = "GfG";
scope is limited to the function. So when you try to print that in function scope, it works. But when you try to access that from outside of that function its undefined behavior.
#include<stdio.h>
#include<stdlib.h>
char *getString()
{
char str[] = "GfG"; // Local variable, so once you try to return that it is undefined
return str;
}
int main()
{
printf("%s", getString());
return 0;
}
Go through the below link you will get some more example. Does local variable be deleted from memory when this function is called in main
Upvotes: 1
Reputation: 91139
In both cases, char str[] = "GfG";
is put on the stack inside the first function. It returns a pointer to that. The caller tries to use it and give it to printf()
, but in the mean time, the "old" stack content was already overwritten.
There may be a difference between them which makes the first one keep the old content a bit longer, but there is no guarantee for that and therefore it is undefined behaviour.
Upvotes: 0
Reputation: 282
Just remember that arrays are not passed by value in C, they are passed by address. Since str
is defined in getstring()
, after the control returns to main()
it is not valid to access that specific address.If you do happen to access the address, the result will be unpredictable. Just remember that the C compiler does not check for incorrect memory access requests in the program.
Upvotes: 1
Reputation: 145899
Because both programs show undefined behavior.
When the getString
function returns the str
array object is destroyed and trying to access it after its lifetime is undefined behavior.
You can fix your program using a string literal, as string literals have static storage duration and their lifetime is the entire duration of the program:
char *getString(void)
{
char *str = "GfG";
return str;
}
Upvotes: 10
Reputation: 18415
You must either allocate the memory with malloc
or try with static
.
Upvotes: 1
Reputation: 42195
char str[] = "GfG";
declares an automatic variable. It is only valid to access this inside the scope it was declared in (the function getString
). Attempting to use it anywhere else results in undefined behaviour. You've been unlucky that the first version appeared to work.
When getString
returns, the stack region used to store str
may be reused. If this happens, printf
will end up reading further through memory until it finds either a '\0'
byte or crashes.
Upvotes: 3