What's wrong with this

D

Droopy

Hi,

I don't understand what's wrong with the following code.
It works in debug mode but generate a System.NullReferenceException in
release mode (see comment to locate the line where this exception
occurs).
I am using VS 2003, Win XP.
This class (SerialBuffer) is a managed C++ class developed to pass a char
buffer to unmanaged C++ legacy code in a mixed mode DLL.
This class is instantiated in C# code.
I made sample code here below to illustrate the problem (simplified as
much as I could).


// code.h

__gc public class SerialBuffer
{
private:
unsigned char __nogc *_buffer;

public:
SerialBuffer (short bufferNr);
~SerialBuffer ();
}

// code.cpp

SerialBuffer::SerialBuffer (short bufferNr)
{
_buffer = new unsigned char [16]; // this line fail in release
mode
}

SerialBuffer::~SerialBuffer ()
{
delete _buffer;
}

// win app code.cs

private void Form1_Load(object sender, System.EventArgs e)
{
SerialBuffer buf = new SerialBuffer (1);
}


Thanks in advance for your help,

Droopy.
 
T

Tamas Demjen

Droopy said:
SerialBuffer::SerialBuffer (short bufferNr)
{
_buffer = new unsigned char [16]; // this line fail in release
mode
}

SerialBuffer::~SerialBuffer ()
{
delete _buffer;
}

If you use new[], you must use delete[]:
delete [] _buffer;

Tom
 
D

Droopy

Droopy said:
SerialBuffer::SerialBuffer (short bufferNr)
{
_buffer = new unsigned char [16]; // this line fail in
release
mode
}

SerialBuffer::~SerialBuffer ()
{
delete _buffer;
}

If you use new[], you must use delete[]:
delete [] _buffer;

Tom

Hi Tom,

You are right but it was a typing error, I have it in my code.
Besides, the exception I got is in the constructor, at startup.

Thanks a lot for your answer.

Any other clue ?

Droopy.
 
V

Vladimir Nesterovsky

Droopy said:
SerialBuffer::SerialBuffer (short bufferNr)
{
_buffer = new unsigned char [16]; // this line fail in
release
mode
}

SerialBuffer::~SerialBuffer ()
{
delete _buffer;
}

If you use new[], you must use delete[]:
delete [] _buffer;

You can get an exception in the operator new if you have heap corrupted.
E.g. check that you do not set _buffer[16] = 0; :)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top