0

I have defined a structure containing a bytes array and its length. The destructor should only delete the byte array if it was dynamically instanced by the structure's constructor. But sometimes, the delete array; instruction fails with error pointer being freed was not allocated. It seems really strange as the array was instanced in the structure. Can anyone help me figure out what's wrong?

typedef unsigned char byte_t;
struct bytes_t {
    bytes_t(varint_t c) : array(new byte_t[c]), count(c), alloc(true) {}
    bytes_t(byte_t b[], varint_t c) : array(&b[0]), count(c), alloc(false) {}
    ~bytes_t() {
        if (alloc)
            delete array;
    }

    byte_t* array;
    varint_t count;
    bool alloc;
};

Edit: Changed a little bit my code, but it still seems to fail. It works when called from the main thread, but not from another thread.

class bytes_t {
private:
    byte_t* const array_;
    const varint_t count_;
    const bool alloc_;
public:
    bytes_t(varint_t c) : array_(new byte_t[c]), count_(c), alloc_(true) {}
    bytes_t(byte_t* b, varint_t c) : array_(b), count_(c), alloc_(false) {}
    ~bytes_t() {
        if (alloc_)
            delete[] array_;
    }
    byte_t* getArray() {
        return array_;
    }
    varint_t getCount() {
        return count_;
    }
};

Edit: I followed @Jens' advice and used std::vector instead. Works like a charm!

Scooter
  • 6,802
  • 8
  • 41
  • 64
neat
  • 63
  • 2
  • 8

1 Answers1

2

There are some issues in your class:

  • When you allocate an array with new[], you must call delete[] instead of delete
  • Your class needs a copy-constructor and a copy-assignment operator
  • The class has only public members which provide a very poor abstraction and no information hiding. You should make the members private and provide a public interface for clients.

Have you considered using std::vector instead of writing your own implementation?

Jens
  • 9,058
  • 2
  • 26
  • 43
  • You're right, thank you. `std::vector` will do the job better than my structure. But, just for the sake of curiosity, I'd still like to know why is this error occurring. – neat Oct 26 '14 at 13:34
  • Could you provide a minimal example which reproduces the error? Otherwise, there are many reasons for problems. I listed some of them, e.g. copying the object results in double deletes, everything is public so other code can manipulate alloc and put the object in a wrong state, wrong delete ... – Jens Oct 26 '14 at 13:38