This question already has answers here:
Can a local variable's memory be accessed outside its scope?
(20 answers)
Closed 8 years ago.
Given the following code snippet:
#include <iostream>
using namespace std;
int *pPointer;
int func()
{
int num;
num = 25;
pPointer = #
}
int main()
{
func();
cout << *pPointer << endl;
cout << *pPointer << endl;
return 0;
}
Can anyone tell me if I duplicate the following line:
cout << *pPointer << endl;
cout << *pPointer << endl;
Why I receive 25 (as expected) but then the next value is 0 (NULL)?
Wouldn't the value of int=25 still remain on the stack? What is it about cout that changes the value of pPointer? Am I missing something about my understanding about scope and the stack? (I'm a Java guy, so this was surprising).
This is because pPointer is pointing to a local variable in func(). This area of memory is only valid inside of the func() method. After func() exits, the memory that pPointer points to is free to be re-used, and appears to be used by cout.
If you want to persist this memory, you should either save it by value, or allocate the memory dynamically pPointer = new int(num)
num does not exist once the function func() terminates.
You take its address when it exists, then attempt to print the value at an address that is no longer valid.
Anything can happen.
As it is undefined behavior, there is no num outside of func scope.
cout << *pPointer << endl;
here *pPointer is pointing to a local variable of some other function which already returned so the address to which it is pointing is out of scope so the behaviour is undefined. it may print the right value assigned to num or may not.
Why I receive 25 (as expected) but then the next value is 0 (NULL)?
What you mention as expected is actually not expected!
num becomes out-of-scope as soon as func() returns. Although pPointer is valid (as it is global), *pPointer is not, because it is pointing to a out-of-scope memory.
Related
This question already has answers here:
Can a local variable's memory be accessed outside its scope?
(20 answers)
Closed 7 years ago.
Here is a simple of example of a question I have:
I create a pointer of integer (value 5), I print the pointer (hence the address) of the memory case it points to, as well as its content (5).
Then I delete that pointer, which is supposed to delete the content in the memory case that has the address of the pointer.
But then when I print a and its content, as expected the address still exists. Nevertheless the content remains the same (5) as if a was not deleted...
could you explain me? :-)
#include <iostream>
int main()
{
int * a = new int(5);
std::cout<< a << std::endl;
std::cout<< "--------" << std::endl;
delete a;
std::cout<< a << std::endl;
std::cout<< *a << std::endl;
// end of my main
return 0;
}
result:
0x7fff28403a90
--------
0x7fff28403a90
5
It may or may not print the same value after delete operation. So simply what you are observing is an undefined behavior.
This question already has answers here:
Can a local variable's memory be accessed outside its scope?
(20 answers)
Closed 8 years ago.
Please consider this simple example:
#include <iostream>
const int CALLS_N = 3;
int * hackPointer;
void test()
{
static int callCounter = 0;
int local = callCounter++;
hackPointer = &local;
}
int main()
{
for(int i = 0; i < CALLS_N; i++)
{
test();
std::cout << *hackPointer << "(" << hackPointer << ")";
std::cout << *hackPointer << "(" << hackPointer << ")";
std::cout << std::endl;
}
}
The output (VS2010, MinGW without optimization) has the same structure:
0(X) Y(X)
1(X) Y(X)
2(X) Y(X)
...
[CALLS_N](X) Y(X)
where X - some address in memory, Y - some rubbish number.
What is done here is the case of undefined behaviour. However I want to understand why there is such behaviour in current conditions (and it is rather stable for two compilers).
It seems that after test() call first read of hackPointer leads to valid memory, but second successive instant read of it leads to rubbish. Also on any call address of local is the same. I always thought that memory for stack variable is allocated on every function call and is released after return but I can't explain output of the program from this point of view.
"Releasing" automatic storage doesn't make the memory go away, or change the pattern of bits stored there. It just makes it available for reuse, and causes undefined behaviour if you try to access the object that used to be there.
Immediately after returning from the function, the memory occupied by the local probably hasn't been overwritten, so reading it will probably give the value that was assigned within the function.
After calling another function (in this case, operator<<()), the memory is likely to have been reused for a variable within that function, so probably has a different value.
You are quite right that this is undefined behaviour.
That aside, what's happening is that std::cout << *hackPointer involves a function call: operator<<() gets called after the value of *hackPointer has been read. In all likelihood, operator<<() uses its own local variables that end up on the stack where local was, wiping out the latter.
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 = # // 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.
This question already has answers here:
Can a local variable's memory be accessed outside its scope?
(20 answers)
Closed 8 years ago.
void foo(int** ptr) {
int value = 4;
*ptr = &value;
// **ptr = value;
}
int main(void) {
int value = 7;
int* ptr = &value;
foo(&ptr);
cout << *ptr << endl; // 4
return 0;
}
My Question is - as the value = 4 is no longer valid/out of scope after returning from foo, why *ptr is showing 4 instead of some garbage value?
Formal answer: undefined behavior.
Practical answer: no other operation on the stack has yet to override that value.
Because you're returning a pointer to a local variable, this is undefined behavior. This includes "appearing" to work, but it's a terrible idea to rely on it in the general case.
In this specific case, the value is left on the stack, and it appears the generated code fetches *ptr just after the call to foo, and before any other function calls. As such, the value has not been overwritten by any other function calls.
If you were to instead insert a function call between the foo(&ptr) and cout << ... statements, the value would more than likely be garbage.
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
}