Sign in to follow this  
3dmodelerguy

knowing when to use delete

Recommended Posts

I have the following code
class instruction
{
	public:
		instruction(opcode code) : _code(code), _data(new char[1]) {}
		instruction(opcode code, const char* data, size_t data_size) : _code(code), _data(new char[data_size])
		{
			memcpy(_data, data, data_size);
		}
		~instruction()
		{
			delete _data;
		}
		opcode code() const { return _code; }
		char* data() const    { return _data; }

	private:
		opcode _code;
		char* _data;
};



however the delete _data(i also have tried delete[] _data) causes a access violation reading location runtime error and don't know why. any ideas?

Share this post


Link to post
Share on other sites
delete [] is the correct form for deleting arrays, but doesn't make any difference in this case. I don't see anything wrong with the code you posted, your error is someplace else.

If you're by any chance running Linux, you should try running your program with valgrind memcheck. That should point the source of your problem right away.

Share this post


Link to post
Share on other sites
When you allocate memory with new, you delete it with delete, and when you allocate memory with new ...[], you delete it with delete [].

For reference, here's a somewhat cleaner version of your code (not compiled or tested!):

class instruction
{
public:
instruction(opcode code) : _code(code) {}
instruction(opcode code, const char* data, size_t data_size) :
_code(code), _data(data, data + data_size) {}

opcode code() const { return _code; }
const char* data() const { return &_data.front(); }

private:
opcode _code;
std::vector<char> _data;
};

As has been mentioned though, we don't have enough information to determine the cause of the error (in particular, it would be useful to know how the data() function is used).

Also, if you're going to use leading underscores, just make sure you know the rules regarding their use as specified by the standard.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this