C++ reference bug [duplicate] - c++

This question already has answers here:
Can a local variable's memory be accessed outside its scope?
(20 answers)
Closed 4 years ago.
I tried to understand how c++ references work and I tried to write the next code:
#include <iostream>
int& func();
int main()
{
std::cout <<func()<< std::endl;
system("pause");
return 0;
}
int& func()
{
int x = 23;
return x;
}
for my understanding, the int x which was initialized in the function will be erased after the func ends and then the value that the function is returning will point to something that doesn`t exist.
But when I print it I get 23 in the console.
How does it possible?

The value is written in the memory inside func(), but you are wrong in "doesn't exist" after return.
Why would it not exist, did anything else overwrite that memory? You can't be sure. It's undefined behavior.
You are just returning a memory adress from func() which after return is made available for other variables. But if that (now available) memory adress is not overwriten, it will hold the value 23.. Until the end of days ;)
Here's #George 's reference to undefined behavior :
https://en.cppreference.com/w/cpp/language/ub
Furthermore your code might have some errors... Anyway, look at this and it shall solve your worries
Can a local variable's memory be accessed outside its scope?

Related

When does a non-dynamic variable goes out of scope if being referenced by a 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.
I'm new to C++ programming and I am having some hard time understanding some concepts.
Take this code as a example:
// Example program
#include <iostream>
class nber
{
int* value;
public:
nber(int n)
{
value = &n;
}
int getNber()
{
return *value;
}
};
int main()
{
nber var(111);
std::cout << "The number is:" << var.getNber() << "\n";
}
As you can see, the nber constructor receives an integer n and passes its address to the "value" pointer. What I expected is to have some kind of unwanted behavior, since the scope of the received integer (n) ends as soon as the constructor end, but the output is:
The number is:111
So the scope didn't end? If it really didn't end, when is the memory used to store the variable n going to be released? Thanks.
The scope did end. What you're seeing is Undefined Behavior - anything can happen. The number could be "purple", as far as the rules say. Or your hard disk could be erased. The latter is a bit rare, though.

C++: Incoherent deletion from the Stack? [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'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.

c++ dangerous pointers practice? [duplicate]

This question already has answers here:
Can a local variable's memory be accessed outside its scope?
(20 answers)
Closed 9 years ago.
#include <stdio.h>
int *pPointer;
void SomeFunction()
{
int nNumber;
nNumber = 25;
// make pPointer point to nNumber:
pPointer = &nNumber;
}
void main()
{
SomeFunction(); // make pPointer point to something
cout<< "Value of *pPointer: "<< *pPointer <<endl;
}
I have been told that using pointers like this is dangerous, could anyone please explain why it is dangerous and what would be the 'safe' way to write that piece of code?
will 25 always be printed out to the screen in that way? if not then why?
Using a pointer to local variable outside of the scope of the variable is always dangerous. It invokes undefined behavior.
Unsafe, because its value may be overwritten
Safe way: just
int SomeFunction()
{
int nNumber;
nNumber = 25;
return nNumber;
}
Will do fine. If your return value is large, return value optimization will save your life anyway.
25 printed? Implementation specified. Most likely not because you are in a new stack frame when the function returned.
You are talkin about wild pointers which termed to be dangerous to use because a pointer, is a memory address, and in modern computers memory is protected (only allowed to be accessed by the program that owns it)
an attempt to read or write to memorry address 0 or NULL will cause your program to crash with a memory violation error.
he best way to protect againsed this to initalise a pointer as soon as it is created.
anouther way, is to test the pointer before using it.
if (pointer == 0) {
cout << "WARNING... cant use this pointer";
}
else {
// it is okay to use this pointer
}

Returning reference of local variables in C++ [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
C++ Returning reference to local variable
Can a local variable’s memory be accessed outside its scope?
In the following code
int& h() {
int o=100;
return o;
}
int main() {
int t=h(); //line 1
cout<<t; //line 2
return 0;
}
Why the output is coming as 100 i.e. the value of the local variable of the function and why there is no error in line 1 because the return type of function is int& but we are returning its return value to a int.
You should never return a reference or a pointer to a local variable. It will be destroyed right when the function returns. It may appear to work in some cases because the stack may not yet be overwritten. But it will fail unexpectedly eventually.
It is legal to assign a reference to something to a value of the same type. So in your assignment a copy is made.
The value is 100 because the memory containing it has just been freed and nobody has written anything to it. Here's another example:
int& h() {
int o=100;
return o;
}
int& h2()
{
int o = 10;
return o;
}
int main() {
int t=h() + h2(); //line 1
cout << t;
return 0;
}
If you compile this with no optimization on Visual Studio, the result will be 20 and here's what will happen:
h() gets called, writes 100 to memory, frees it and returns a reference.
h2() gets called and writes 10 to the same place in memory (it has been freed before)
main() computes the sum of 2 values from the same place in memory. Thus, it's 10+10.
Setting int from int & is not an error. It's a valid operation that means "take this reference to some object and copy whatever is there to my local variable".
Return reference local variable - for single thread application /example by Ivan/ is not problem. For multithread application is problem - when diferent threads use function e.g. h(). In this case may be moments, when threads cross used unallocate memory.
Compilers don't necessarily protect against bad and/or undefined behavior.
Check what options you're passing to your compiler.
Compiling your code at codepad.org produces a warning: http://codepad.org/ParI4AOG
In function 'int& h()':
Line 6: warning: reference to local variable 'o' returned

I can't understand why this program prints 8762 as a result [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Can a local variable's memory be accessed outside its scope?
#include <iostream>
double *foo(){
double *varFoo = new double;
double temp = 8762;
varFoo = &temp;
return varFoo;
}
int main(void){
double *newVar = foo();
std::cout<<*newVar<<std::endl;
std::cin.get();
return 0;
}
I understand that the pointer varFoo will be created in the heap and thus will stay there until I call delete, but what about temp variable which is inside the function foo?
it's a local variable and as soon as the call of the foo function ends, the address where the temp variable's values will be stored will just be freed right?
so why do I get 8762 as a result instead of rubbish?
thanks
Because you are in Undefined Behavior land. Anything could happen.
Moral of the story: never return the address of a temporary!
No it won't necessarily be freed right away. The data will still be there in memory until something else writes over it. Since your program does not do much after calling the function, there is not an opportunity for the value to be overwritten so it is still "correct".
so why do I get 8762 as a result instead of rubbish?
8762 is rubbish.