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.
Related
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.
This question already has answers here:
returning a local variable from function in C [duplicate]
(4 answers)
Closed 8 years ago.
I'm studying for exams right and i've come across this question:
What is the crucial error in this code?
int *numbers(int a, int b)
{
int array[2];
array[0] = a * b;
array[1] = a + b;
return array;
}
Now, I don't have much C experience but I don't see a crucial error in this code at all. Maybe I'm being a moron and just overlooking something obvious. The only thing I can see is memory hasn't been allocated using malloc but I don't see that a big problem.
Any help is appreciated!
The most basic problem here is that array ceases to exist as soon as numbers() returns. The returned pointer is pointing to space that will likely be overwritten in just a moment.
The variable array will disappear when the function returns, but you have returned a pointer to its place in memory.
You are basically returning garbage, because array will go out of scope after return. If you make array static everything will be OK.
If memory WAS allocated with malloc, then the function would be valid. Once the function exits, any memory that was allocated within the scope of the function (stack) is no longer valid.
This question already has answers here:
Can a local variable's memory be accessed outside its scope?
(20 answers)
Closed 8 years ago.
Though a similar question has been asked Is it possible to deallocate a statically defined array? previously, I have a related query.
int* foo()
{
int arr[3] = {1, 2, 3};
return arr;
}
int bar(const int*)
{
doSomething with int*;
}
int main()
{
bar( foo() );
}
When will the memory allocated to arr in foo() be deallocated? Is a statically allocated array like arr not usually automatic? This syntax seems to work though, so is the memory assigned to arr only deallocated after the completion of bar()? Or not even then? If not, how would I free it?
Edit: Sorry, forgot to include main. Yes, this appears to be a duplicate post.
Your array behaves like a normal variable, as it actually is one.
The variable scope in C or C++ is usuablly definied by the current block, which is your function foo.
As your array arr lies within the stack-area of your programm you should never every return a pointer to a local variable.
The stack-memory section is invalidated after your foo function returns and so you would access to not permitted memory area if you dereference the return value of foo. This leads to undefined behaviour. So everything can break or nothing. But this is just not what you want.
If you want to return a more long living array, you allocate memory in the heap-memory-section by creating your array with new or malloc. Than you can access it after your foo-function returned. But you have to free or delete[] your array than by hand.
You should maybe read more about memory-layout in C/C++: http://www.geeksforgeeks.org/memory-layout-of-c-program/
Most likely, it will be created on the stack inside the call to foo. When foo exits, the stack pointer is reset. The array is considered no longer accessible.
You can still see it because your program owns the memory where the stack is. However, once something else gets pushed onto the stack, it will get overwritten.
So, you should not use it outside of foo.
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.