Drew Chapin
Drew Chapin

Reputation: 8009

new/delete causes access violation

Ok, this is perplexing me... The code below is in a DLL, and when my console application calls this code it is suddenly throwing an access violation at the line delete[] lpBuffer. I have been using this code all day and have not changed it at all. Until now, it had been working just fine.

Access Violation Message

Unhandled exception at 0x6948b1a5 in rhcopy.exe: 0xC0000005: Access violation reading location 0x4de1c37f.

Library Code

#define MAX_PACKET_SIZE  0x3FFF

DWORD MyClass::GetFile( LPCSTR lpszRemoteFile, LPCSTR lpszLocalFile )
{
    LPBYTE lpBuffer = NULL;

    // ...

    lpBuffer = new BYTE[MAX_PACKET_SIZE];

    // ...

    if( NULL != lpBuffer )
        delete[] lpBuffer;

    // ...
}

Am I doing something wrong?

On a side note: I have been thinking about converting lpBuffer into a vector. Opinions?

edit

I want to thank you guys for your help! But apparently... That's not where the problem is. problem is actually a printf() statement in the calling application that occurs right after the call to GetFile(...). I apologize for the confusion. It would seem that Microsoft's Debugging tool is not pointing to the line that caused the error, but rather the last line that executed. I have voted to close the question.

Upvotes: 0

Views: 7390

Answers (2)

Mark Ransom
Mark Ransom

Reputation: 308520

There is nothing wrong in the code you've shown here.

Two possibilities come to mind:

  1. The error is not actually in the delete but in the code just on either side.

  2. You've done something to corrupt the heap, by using an invalid pointer that overwrites some random memory or deleting a pointer more than once.

Neither of these problems would be caught by switching to RAII (i.e. vector) in the displayed code, but might improve things if you used them consistently in the rest of your code.

Upvotes: 4

Joel
Joel

Reputation: 2966

I'm not really sure why an access violation is caused here given the code posted.

Since the buffer is only referenced locally could you make it a stack variable instead of allocated dynamically?

If it must be a pointer maybe you could use a Boost Smart Pointer instead:

#include <boost/scoped_array.hpp>

#define MAX_PACKET_SIZE  0x3FFF

DWORD MyClass::GetFile( LPCSTR lpszRemoteFile, LPCSTR lpszLocalFile )
{

    boost::scoped_array<BYTE> bufferPtr;
    ...
    bufferPtr = boost::scoped_array<BYTE>(new BYTE[MAX_PACKET_SIZE]);
    ...
    //No delete needed

}

On the vector point, if it's easy to work with a vector I'd opt for it or any other STL Container when you can.

Upvotes: 1

Related Questions