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!
 
     
    