knowing when to use delete

Started by
5 comments, last by Zakwayda 15 years, 11 months ago
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?
Advertisement
I have and still get the same error.
In your data function you hand out your char* are you deleting that somewhere else?
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.
The issue was i did not have a copy constructor.
So... you didn't define a copy-ctor, but had a compiler generated one which did a shallow copy of the ptr in _data, causing a double-delete after the copy.
[size="1"]
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.

This topic is closed to new replies.

Advertisement