Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does a pointer change itself during function transition?

Tags:

c++

pointers

In the following case I'm calling a Func with pointer passed to it, but in the called function, the parameter shows the pointer value as something totally bogus. Something like below.

bool flag = Func(pfspara);--> pfspara = 0x0091d910 

bool Func(PFSPARA pfspara) --> pfspara = 0x00000005
{
    return false;
}

Why does pfspara change to some bogus pointer? I can't reproduce the problem in debug, only in production.

Thanks.

like image 537
Prache Avatar asked Oct 18 '08 06:10

Prache


People also ask

Can pointer value be changed?

We can change the pointer's value in a code, but the downside is that the changes made also cause a change in the original variable.

Does the address of a pointer change?

Pointer addresses usually change due to Address space layout randomization . When it is disabled (Windows and Linux) then addresses no longer change between program executions. Pointer addresses used to be constant between executions.

Why does the type of pointer matter?

The data type of pointer is needed when dereferencing the pointer so it knows how much data it should read. For example, dereferencing a char pointer should read the next byte from the address it is pointing to, while an integer pointer should read 4 bytes.

Can a pointer be nil?

Nil Pointers All variables in Go have a zero value. This is true even for a pointer. If you declare a pointer to a type, but assign no value, the zero value will be nil .


2 Answers

If you are trying to debug optimized code in for example Visual Studio, you cannot always rely on the debugger properly showing the values of variables - especially not if the variable is unused so that the compiler probably optimizes it away.

Try running this instead:

bool Func(PFSPARA pfspara)
{
    printf("%x\n", pfspara);
    return false;
}
like image 200
Rasmus Faber Avatar answered Oct 07 '22 01:10

Rasmus Faber


In general, this should never happen. Problems that can cause this type of symptoms include incompatibility in the compilation options between the calling and the caller modules, bad casting of member function pointers, or simply compiler bugs. You need to provide a lot more details about your problem: Show the real code, specify your compiler, specify what are the debug vs. production compilation flags, etc.

like image 43
Oren Shemesh Avatar answered Oct 07 '22 00:10

Oren Shemesh