This question already has answers here:
How to access a local variable from a different function using pointers?
(10 answers)
Closed 6 years ago.
If I understand correctly, variables that are not dynamically allocated are supposed to be deleted at the end of their scope.
However, I wanted to try it out with this code (which I think is not correct as I am supposed to use dynamic allocation) :
int* function()
{
int a = 3;
return &a;
}
int main(int argc, char const *argv[]) {
int* a(function());
std::cout << *a << std::endl; // prints 3
}
Why can I still access the value of the variable a by using the pointer returned by the function when it is supposed not to exist anymore ?
a and hence the return value from function has gone out of scope. You are just lucky.
Just be careful and compile with all the warnings enables - and take heed of those warnings.
The fact that you can access the value is pure luck. The code has undefined behaviour (since the variable is destroyed) and the compiler can generate whatever it wants - but you cannot rely on it.
Related
This question already has answers here:
Return a pointer that points to a local variable [duplicate]
(3 answers)
Closed 2 years ago.
void* func1(int a)
{
void *b = &a;
return b;
}
int main(int argc, char** argv) {
int d = 9;
void *c = func1(d);
printf("%d\n", *((int*)c));
return 0;
}
I am confused about why it works.
From my understanding, memory of "a" will release after func1.
Why the void* c can still access "a" after finish the function?
I am confused about why it works.
The behaviour of the program is undefined. The program doesn't "work" - In my opinion. Although "workingness" may be subjective.
From my understanding, memory of "a" will release after func1.
Correct.
Why the void* c can still access "a" after finish the function?
Behaviour of the program is undefined. Appearance of having particular behaviour is within the limits of undefined behaviour. Anything is within limits of undefined behaviour because the language imposes no limits on behaviour of the program.
This question already has answers here:
Can a local variable's memory be accessed outside its scope?
(20 answers)
Closed 5 years ago.
I'm trying to understand how to use functions in C++ to return arrays. I want to understand what's going on here. This is my code, that I compile with g++ -Wall return_array.cpp -o return_array
#include <iostream>
int * do_something(int number){
int viz[3] = {1,2,3};
viz[2] += number;
return &viz[0];
}
int main(){
int *viz;
viz = do_something(3);
std::cout << viz[2] << "\n";
return 0;
}
which gave me the following error:
return_array.cpp: In function ‘int* do_something(int)’:
return_array.cpp:4:6: warning: address of local variable ‘viz’ returned [-Wreturn-local-addr]
int viz[3] = {1,2,3};
By my research, the error is due to the fact that I'm trying to access a pointer that has been deleted from the Stack once I leave the function's scope. However, if I run the code with a workaround:
int * do_something(int number){
int viz[3] = {1,2,3};
int *pointer;
viz[2] += number;
pointer = &viz[0];
return pointer;
}
it compiles and runs just fine. Isn't this new pointer in the precise same situation? Once I leave the function, it is out of scope and should be deleted from the Stack, by the same argument as before. What am I missing?
EDIT:
My question here is not whether or not returning the pointer to a local array produces an error. It should and it does. The question is why the pointer that has been assigned to the pointer to the same array does not!
Once control leaves the function, the array is out of scope. It might be erased, it might not. That region of memory might still contain those numbers for a while, and it might not. Trying to read it might work, or it might do anything. This is known as undefined behavior, and it is a difficult thing to detect and a good thing to avoid.
This question already has answers here:
C++ return value without return statement
(6 answers)
Closed 6 years ago.
I am confused with the following output in C++
int add()
{
int c = 2+3;
}
int main()
{
int x = add();
cout << x;
return 0;
}
This prints 5.even if we do not write return statement.
How this is managed in C++.
Please help.
This is UB. You're right to be confused - this can work one day and fail the next. Don't rely on undefined behavior.
If you want to know why it works, it's because parameters & return values are passed on a data structure called stack (well - usually; sometimes passed in the same register). Similarly, most implementations use this same stack for locals. Therefore, the int in add will be located in the same place as where the return value is expected (by your specific implementation) and your implementation doesn't invalidate memory when your int there is destructed. But it's still destructed, it's still UB and it might break in any second.
As the comments wrote, you might turn on warnings to avoid this kind of error.
This question already has answers here:
How to access a local variable from a different function using pointers?
(10 answers)
Can a local variable's memory be accessed outside its scope?
(20 answers)
Closed 6 years ago.
This is my C++ code .
According to me , it should give output:
abc
Garbage
abc
But it is giving output:
abc
Garbage
Garbage
#include<bits/stdc++.h>
using namespace std;
char **func()
{
char* PA = new char[10];
PA[0]='a';
PA[1]='b';
PA[2]='c';
PA[3]='\0';
printf("%s\n",PA);
printf("Garbage\n");
char **PPA = &PA;
return PPA;
}
int main()
{
printf("%s\n",*func());
return 0;
}
Where am I doing wrong?
char **PPA = &PA;
Retrieves the address of the variable PA itsself, which is an automatic variable and goes out of scope as soon as the function terminates. That means you have undefined behavior here. The C standard doesn't guarantee any consistent behavior, so anything may happen, including what you experienced.
To fix that, you could change the function prototype to char* func() and return PA directly and remove PPA altogether.
This question already has answers here:
How is a variable at the same address producing 2 different values? [duplicate]
(4 answers)
Closed 8 years ago.
Both &i(inside main function) and p(inside func function) holds the same address. Well I know that a constant object/variable cannot be modified but I'm able to increment the variable i using (*p)++ in the func function, but the result is not reflecting in the main function. Why is that?
#include <iostream>
using namespace std;
void func(int *p){
(*p)++;
printf("%p %d\n", p, *p);
}
int main(int argc, char **argv){
const int i = 47;
const int *p = &i;
func(const_cast<int *>(p));
printf("%p %d\n", &i, i);
return 0;
}
I'm getting this output:
000000000022fe44 48
000000000022fe44 47
Because of undefined behavior. You are modifying constant data. That const_cast should be a big hint.
Object declared const at point of it's definition is truly a const object. That mean results of modifying that object is undefined.
Undefined means it's totally upto the compiler what it wants to do with your code. In your case, it seems compiler allocated that truly const in read only memory. When you passed this to function taking non-const pointer, compiler might have provided that function with another memory containing similar value. But that's just my speculation.
EDITED in response to comment by #FreeNickName:-
Since addresses of both pointers ( one in main and other in func )are same, I think above is not giving correct/complete picture what's going on under the hood. Maybe compiler is just ignoring that increment instruction as it is being applied on memory that's read only.