c++ dangerous pointers practice? [duplicate] - c++

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
}

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++ reference bug [duplicate]

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?

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.

Pointers pointing to variables(located on the stack) - C++ [duplicate]

This question already has answers here:
Can a local variable's memory be accessed outside its scope?
(20 answers)
Closed 8 years ago.
I guess this is a very basic question, but even after looking around on the internet for a while I can't seem to find a proper answer to this question.
I will refer to this tutorial on stack/heap:http://gribblelab.org/CBootcamp/7_Memory_Stack_vs_Heap.html
Let's say I write the following code:
void testVoid() {
int testVariable = 5;
}
If I'm not wrong, this function should create a variable located on the stack. As the functions exits, the allocated memory on the stack is deleted - so my variable should also have been deleted by then.
I have learned that pointers in c++ point to the memory location of a variable.
So if the variable pointed to by a pointer is located on the stack, and the stack then is cleared, I would expect not to be able to access original value through the pointer anymore, since the memory location pointed to is is cleared. However, I tested this:
int* pointer;
void testVoid() {
int num = 3;
pointer = &num; // Here I get the memory location of my num-variable
cout << pointer << " : " << *pointer << endl; // I would get the same result if i printed &num
}
int main(int args, char** argv) {
pointer = new int;
testVoid();
cout << pointer << " : " << *pointer << endl; // I can still access the memory of my num-variable
while (true) {}
return 0;
}
After exiting the testVoid()-function, where the variable is created, I can still get the value of the variable using my pointer. So obviously I have misunderstood something regarding how pointers work in c++. Printing &pointer and &num gives me the same memory location, even after testVoid() has finished. What is the reason for this? If the memory pointed to by the pointer were moved to the heap, shouldn't cout<<&num and cout<
And here's the output:
0024F904 : 3
0024F904 : 3
Just because the value goes out of scope does not mean the memory for the value has been overwritten. You just can't rely on it being stable at that point.

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.