This question already has answers here:
Can a local variable's memory be accessed outside its scope?
(20 answers)
Closed 2 years ago.
#include<stdio.h>
#include<stdlib.h>
int *p;
void f()
{
int a=5;
p=&a;
printf("%d ",*p);
}
void main()
{
f();
printf("%d",*p);
}
Why the O/P is 5 5?
After the function call is over then the local variable a is removed. So p should be pointing to invalid object
If it is undefined behavior then it is also allowed to (occasionally) give the output of 5. But don't be surprised if the next morning it gives out 6.
Why is the Output 5 5?
It is because of something called "Undefined Behavior". Undefined Behavior do not have to always provide the wrong result.
After the function call is over then the local variable a is removed. So p should be pointing to invalid object.
Exactly, it is pointing to an invalid object or better said to no object at all - the int object of a allocated inside of the function f() is already deallocated at the point of executing printf("%d",*p); in main().
To dereference a pointer with an stored address to an no longer existant object is Undefined Behavior.
It could print out anything. That it print out 5 is just a lucky shot, but never reliable. Even when executing the exact same file a second time, you already could get a different result.
Related
This question already has answers here:
Can a local variable's memory be accessed outside its scope?
(20 answers)
Closed 5 years ago.
I've a question about var scopes and pointer.
That's an example function:
int *double(int a)
{
int p = a*2;
int *ret = &p;
return ret;
}
And that's the question:
After a fuction return to the caller, it should delete from the memory every variable declared in it.
In this function I only return the addres of "p" (that's declared only in the function) but when I use it in the main, for example, the space of memory allocated by the function "double" hasn't been deleted.
Why?
The memory isn't valid anymore; what happens when you access it after double has returned is undefined behavior. That means that anything is possible:
It could be that the value hasn't been overwritten by something else yet (what likely happened in your case).
It could be that something else has written something to that address, so the value is now random garbage.
It could be that your code opens up a wormhole to a parallel dimension, causing an invasion of evil space octopi that dooms us all.
So, basically, I don't recommend it.
This question already has answers here:
Returning local data from functions in C and C++ via pointer
(13 answers)
Can a local variable's memory be accessed outside its scope?
(20 answers)
Closed 5 years ago.
#include<stdio.h>
#include<conio.h>
int *x()
{
int y=10;
return (&y);
}
void main()
{
int *p;
clrscr();
p=x();
printf("%d",*p); // Output 10
getch();
}
Here when we call x() function, activation record of x is pushed onto the stack. When we come out of that function, the activation record and all the local variables inside it are destroyed.
So, how are we able to access the value of y in main function after coming out of x function ? The output value should be some garbage value as "y" variable is destroyed.
Function x returning a pointer to an automatic local variable and causing undefined behavior. In this case any expected or unexpected result can be seen.
Local variables have a limited lifetime which only extends inside the block {} they are defined. They have a local-scope.
When the control reaches the end of the block all the storage for the variables in it is not guaranteed to not be writable.
That portion of memory can be re-used. Will it be? who knows.
This translates to: undefined behaviour!
Is not like "y" gets destroyed.
Its memory region is labelled as "writable"
So you may either find your "y", as well as a garbage value.
After all, the function is returning a pointer, not the variable itself
This question already has answers here:
Can a local variable's memory be accessed outside its scope?
(20 answers)
Closed 6 years ago.
#include<stdio.h>
int* add(int *a, int *b){
int c = *a + *b ;
return &c;
}
int main(void) {
int a=3,b=2 ;
int *ptr = add(&a,&b); // doubt in this line as it returns 5
printf("%d",*ptr);
}
I have doubt in the line commented.
I am using Codeblocks IDE(GNU gcc compiler), and I was wondering that if the *ptr in my main is pointing to the address of c in the add function, then it should print garbage as after the function `add completes its execution, it's popped from the stack, and the memory should be deallocated for it in the stack . So technically, it should be pointing to garbage. Then how is it printing the correct value.
You have undefined behavior, as you are returning the address of a function-local variable. A good compiler with warnings enabled would tell you this.
When you have undefined behavior you don't get to complain about the results. There is no need to wonder why it gives you the "correct" result because it does not--it gives you some number which may or may not be correct depending on any number of factors you don't control.
I think this is undefined behavior. On my system this example crashed with a segmentation fault. When something is deallocated, it is possible that the pointer to that memory location is simply moved without zeroing out the memory.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Can a local variable's memory be accessed outside its scope?
I recently came across the following code:
#include <stdio.h>
int* abc () {
int a[3] = {1,10,100};
return a;
}
int* xyz () {
int b[1] = {222};
return b;
}
int main() {
int *a, *b;
a = abc();
b = xyz();
printf("%d\n", *a);
return 0;
}
the output is 222. 'a' is pointing to the array declared inside the xyz().
my question is:
why is a pointing to the array declared inside xyz().
the array declared inside the function xyz() should go out of scope after the execution of the function. why is that not happening ?
2: It is happening, and the entire program has undefined behaviour. It is not a correct program, and there's little point musing about ifs and buts.
You might see 222 because the memory that was used for the local array in abc has been used for something else - the stack for the function xyz. And you're passing around an address to that memory. Make a few more function calls and *a may contain some other value.
should go out of scope after the execution of the function. why is that not happening ?
The variable has gone out of scope. Using that address outside the function is incorrect code: using a pointer to local data returned from a function is undefined behavior.
The variables a and b are automatic variables; using their adress in a other function is an undefined behavior. Anything can happen : you can't expect an output (eg, an optimizing compiler can delete some illegal code).
to return a pointer it must be a pointer to dynamically allocated variable or static or global variable.
returning a pointer to a stack variable will cause you to have pointer to the stack which will be reused when you call a new method.
it happened in your case to reuse the stack variable for another array and overwrite the old value stored when you called the first method.
try to call printf again you will see different output because the first call to printf changed the stack content.
why is that not happening ?
It does happen, just formally. Undefined behavior is not obligated to crash or to misbehave - they "anything might happen" means it can also run seemingly without any error. I just answered a similar question.
The functions abc and xyz are each passing back an address to a locally created array. Subsequent calls are mashing the memory that was previously used (and passed back to you).
These are called automatic local variables.
You'll need to declare those arrays as static or allocate the memory in a different way.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Can a local variable's memory be accessed outside its scope?
I was refreshing the knowledge about how memory internally works, and I faced the confusion. Here is sample code
int * func(){
int retval = 3;
return &retval;
}
int main(void){
int *ptr = func();
printf("address return from function %p and value %d\n", ptr, *ptr);
}
My understanding regards how stack memory works on a routine, is when a function was called, it is pushed on the stack. And lifetime of local variables within this routine would no longer valid once the function returns. So returning address of local variable seems like not valid, but when I test this code, it actually returns its address and still valid after the function returns.
am I misunderstanding the concept ? Appreciated any comments, Thanks.
"Testing the code" is not a meaningful way to determine if something is valid or not. Your code produces undefined behavior. One possible manifestation of undefined behavior is that the code might appear to be "working". In other words, you simply got lucky.
To answer the question: no, it is not valid to return a pointer to a local variable and it is not valid to dereference such a pointer. Any attempts to do so lead to undefined behavior.