Garbage value retrieval [duplicate] - c

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

Related

why does returning the local variable address throws an error but returning the local variable value don't? [duplicate]

This question already has answers here:
Why is a runtime error is produced when we return a local address but not a local variable?
(1 answer)
How to access a local variable from a different function using pointers?
(10 answers)
Closed 10 months ago.
I can not understand, what is the difference between following function bodies
int func(void){
int A = 20;
return A;
}
and
int* func(void){
int A = 20;
return &A;
}
why returning the values does not throw the error of the segmentation fault but returning the address do?
Attempting to target the more specific question asked in follow-up comments on several other answers:
if the address of the local variable after the scope gets deleted then how the value of that address preserved? in case of returning local variable value from the function? this is I can not understand
Returning a value makes a copy of that value, into a storage location provided by the caller. You presumably have something like
void call_func(void) {
int n = func();
printf("%d\n", n);
}
as the function that calls func -- so, when func returns the value of A, that value gets copied into n.
Returning a pointer to A is actually exactly the same: a value is copied into a storage location provided by the caller. Only now the value that gets copied, is the address of the storage location formerly occupied by A.
A local variable with automatic storage duration is not alive after exiting the scope of the function where it is defined. So the returned pointer will be invalid and de-referencing such a pointer invokes undefined behavior.
If you will change the second function the following way
int* func(void){
static int A = 20;
return &A;
}
then returning a pointer to the variable A will be correct because the variable having static storage duration will be alive after exiting the function.
A returned value can be assigned to a variable or discarded. So there is nothing wrong.

Global pointer and dangling pointer [duplicate]

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.

Address of the automatic storage class variable assigned to a local variable of another function [duplicate]

This question already has answers here:
Can a local variable's memory be accessed outside its scope?
(20 answers)
How to access a local variable from a different function using pointers?
(10 answers)
Closed 4 years ago.
#include <stdio.h>
int* function1(void);
int main()
{
int x = 10;
int *p = function1();
printf("%d\n", *p);
printf("%d\n", p);
}
int* function1(void)
{
int z;
z = 20;
z++;
return &z;
}
Variable 'z' is local to the 'function1', and is not alive after the
'function1' is terminated.
Now to access the value at the memory space of the variable 'z', its
address is returned by the function.
So, even after the termination, will the memory space of the variable
'z' will still be reserved, as the pointer accesses the variable?, in such case what will be the properties of the memory space?
Or What if some-other variable is allocated with the same memory space
of variable 'z'?
Note: GCC compiler of code blocks has compiled the program successfully, without any error and warning.
In general what you do is undefined.
However, on Intel architectures z is on the stack and after return, if you don't call any other function the value will probably still be available because the memory has not yet been reused. As soon as you call another function, the memory will probably be overwritten and so will contain garbage for you.
In general: Don't do this!
The variable z does no longer exist after the function function1 finishes it's execution. In function main you are trying to reference a memory address which has been deallocated after the function's call. This will cause undefined behavior.
When the function call happens, all your local variables will be in stack. During function call, the stack variables can be modified. When the function call returns, the stack pointer is decremented’
Hence, you will be accessing something which is not guaranteed in any way. In programming languages, this is addressed as a case of undefined behaviour, since you are overriding the rules of programming language.
In this case of function, given that you stack frame is still active and not modified by any other code, you might get the same value that you wrote to that address.
But is not guaranteed in anyway and dont assume anything not guaranteed.

C pointers and var scopes [duplicate]

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.

strange behavior in c [duplicate]

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.

Resources