Search code examples
c++visual-c++visual-studio-debuggingvisual-studio-2015

Returning from Function changes context to NULL


I have three classes relevant to this issue. I'm implementing a hardware service for an application. PAPI (Platform API) is a hardware service class that keeps track of various hardware interfaces. I have implemented an abstract HardwareInterface class, and a class that derives it called HardwareWinUSB.

Below are examples similar to what I've done. I've left out members that don't appear to be relevant to this issue, like functions to open the USB connection:

class PAPI {
    HardwareInterface *m_pHardware;

    PAPI() {
        m_pHardware = new HardwareWinUSB();
    }

    ~PAPI() {
        delete m_pHardware;
    }

    ERROR_CODE WritePacket(void* WriteBuf)
    {
        return m_pHardware->write( WriteBuf);
    }
};

class HardwareInterface {
    virtual ERROR_CODE write( void* WriteBuf) = 0;
};

class HardwareWinUSB : public HardwareInterface
{
    ERROR_CODE write( void* Params)
    {
        // Some USB writing code.
        // This had worked just fine before attempting to refactor
        // Into this more sustainable hardware management scheme
    {
};

I've been wrestling with this for several hours now. It's a strange, reproducible issue, but is sometimes intermittent. If I step through the debugger at a higher context, things execute well. If I don't dig deep enough, I'm met with an error that reads

Exception thrown at 0x00000000 in <ProjectName.exe>: 0xC0000005: Access violation executing location 0x00000000

If I dig down into the PAPI code, I see bizarre behavior. When I set a breakpoint in the body of WritePacket, everything appears normal. Then I do a "step over" in the debugger. After the return from the function call, my reference to 'this' is set to 0x00000000.

What is going on? It looks like a null value was pushed on the return stack? Has anyone seen something like this happen before? Am I using virtual methods incorrectly?

edit After further dissection, I found that I was reading before calling write, and the buffer that I was reading into was declared in local scope. When new reads came in, they were being pushed into the stack, corrupting it. The next function called, write, would return to a destroyed stack.


Solution

  • After further dissection, I found that I was reading before calling write, and the buffer that I was reading into was declared in local scope (in the read function).

    When new reads came in, they were being pushed into the stack, corrupting it. The next function I called, write, would return to a destroyed stack.