Prache
Prache

Reputation: 543

Why does a pointer change itself during function transition?

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.

Upvotes: 5

Views: 1530

Answers (5)

Zebra North
Zebra North

Reputation: 11492

It sounds to me like you're scribbling on the stack... somewhere in your code a buffer on the stack is overflowing, or you're taking the address of an object on the stack and writing to it after the function returns. This is causing your stack to be corrupted.

It may only happen in release mode because the stack allocations are different due to optimization and exclusion of 'guard' blocks used to help check for this kind of condition.

Upvotes: 0

Head Geek
Head Geek

Reputation: 39888

It sounds like a buffer overflow problem to me -- something is overwriting that variable. But as mentioned in other answers, there's no way to tell for sure without some actual code to work with.

Upvotes: 0

SmacL
SmacL

Reputation: 22932

In addition to Rasmus' comments, I find it is generally worth checking whether the problem occurs in a debug build as well as the release build. If you see genuine problems occurring in a release build but not in the debug build, it is often down to a bug that is exposed by the optimization processs, such as an uninitialised variable. There is a real danger in doing most of your testing in a debug build, to avoid the problem you are seeing here, and then shipping a release build. IMO, if you don't have a good regression test suite (preferably automated) I would avoid shipping opimized code.

Upvotes: 0

Rasmus Faber
Rasmus Faber

Reputation: 49687

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;
}

Upvotes: 8

Oren Shemesh
Oren Shemesh

Reputation: 1578

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.

Upvotes: 1

Related Questions