Writing to a class pointer gives me an access violation error
Please view this image of the crash after I choose to debug it in MVS2010: http://i48.tinypic.com/dr8q9u.jpg
Here's the Game.h header that shows the Game class structure, and in the picture you will see the offending method that's causing the access violation (setBot(botInfo * b)
).
class botInfo; // Forward declaration
class Game {
int gameState;
int flagDropTime;
botInfo * bot;
public:
Game();
~Game(void);
void startGame();
void gameOver(int victoriousTeam);
void resetBall();
void hideBall();
int getState();
void setBot(botInfo * bot);
botInfo * getBot();
};
From an instance of botInfo (another class) I'm calling a function with this code, (Game _dsbTrench is a member variable of the botInfo instance).
botInfo * botPointer = this;
_dsbTrench->setBot(botPointer);
Problem is, whenever I call this it causes an exception: Unhandled exception at 0x72332569 (PubBot.dll) in MERVBot.exe: 0xC0000005: Access violation writing location 0xcdcdcdd5.
So whats the cause of this error? And how can I fix it?
Tha开发者_JS百科nks.
For more details on the various memory states 0xCDCDCDCD, 0xDDDDDDDD and so on this is a great reference:
http://www.nobugs.org/developer/win32/debug_crt_heap.html
0xCDCDCDCD is a flag value that the MS C runtime uses to fill newly allocated memory. In your "_dsbTrench->setBot(botPointer);", _dsbTrench is 0xCDCDCDCD - which is obviously a bogus pointer. Chances are you forgot to initialize that variable.
I don't think there is enough information for me to help. But I will try.
You are writing to memory that is not assigned to your program by the operating system -- you need to allocate the memory before you write to it.
- You should not be passing the this parameter to other functions -- your offset calculations are probably off -- can't you use a reference ? .
- Have you allocated memory for dsbtrench ?
-- edit --
As mentioned by the other answers"0xCDCDCDCD" is a sentinel variable used for uninitialized words.
did you debug that code? it seems that _dsbTrench is null when you call setBot method for it. passing "this" pointer is ok as long as you know what you are doing with it :)
精彩评论