How to use Pointer for stack variable using C++?

(Sine) #1

i have the following two C++ methods:

inline void ApplyValue(ulong** IntPtr)
    // Now this 'some_value' variable is declared only in the containing method's
    // stack scope, thus its value "0xDEADBEAF" should only be avaialble in stack 
    // within the containing method "ApplyValue".
	ulong some_value = 0xDEADBEAF;
	*IntPtr = &some_value; // Now we have a pointer to our local in stack pointer value.
int TestMethod1()
	ulong* SamplePtr = NULL;
	// Somehow though the source value Pointer, is local to the ApplyValue method,
	// Thus, should not be avaialble here, the C++ outputs the correct value
	// Loaded within the Child method.
	cout << *SamplePtr << endl;
	return 0;

I believe my problem is self-explanatory from the two methods above, So isn’t it supposed that the Output be invalid or some other value other than “0xDeadBeaf” as that value is only local to the ApplyValue() method?

( #2

The Variable being removed from the stack doesn’t mean it’s memory address is not accessible anymore or changed, Just since in your program you displayed the pointer Value directly after the method return, so the Stack wasn’t changed or used before the old variable pointer value was displayed.

Mainly you should not use that method as you have almost no guarantee of how the Stack behaves thus the expected behavior will be unknown.