mitchelllc
mitchelllc

Reputation: 1657

destruct struct array member in C++

I have a problem about destructor. In below main.cpp, if I define ht as a pointer, the program works fine. But if I define ht as an object, it will throw an error

"malloc: * error for object 0x7fff511a4b00: pointer being freed was not allocated * set a breakpoint in malloc_error_break to debug"

I understand this error and my solution is to define ht as a pointer.

My question is whether I can define ht as an object directly or not, if the answer is yes, how should I modify the class definition.

Thanks.

main.cpp

#include "copy_constructor.h"

int main()
{
  // Define ht as pointer works fine
  //Hash_Table<int>  *ht;
  //ht = new Hash_Table<int>;

  Hash_Table<int> ht;

  // keyed_structure<int> s;
  //  s.data_val = 10;

  return 0;
 }

copy_constructor.h

#ifndef COPY_CONSTRUCTOR_H
#define COYP_CONSTRUCTOR_H

#include <cstdlib>
#include <iostream>

const size_t MAX_SIZE = 3;

template<class D> struct keyed_structure
{
  size_t key_val;
  D data_val;
  bool empty_val;
};

template<class D> class Hash_Table
{
  public:
    // COnstructor
    Hash_Table() {
      //h_table = new keyed_structure<D> [MAX_SIZE];
      for (size_t index=0; index < MAX_SIZE; ++index) {
        h_table[index].empty_val = true;
      }
    }
    // Destructor
    ~Hash_Table() {
      //std::cout << "Do destruct" << std::endl;
      delete[] h_table;
    }

  private:
     keyed_structure<D> h_table[MAX_SIZE];
};

#endif

Upvotes: 0

Views: 895

Answers (2)

billz
billz

Reputation: 45410

You don't need to call delete[] h_table; as you didn't new anything in Hash_Table. Your code is undefined behavior.

The reason your test doesn't crash is because you only new ht but didn't delete ht

  Hash_Table<int>  *ht;
  ht = new Hash_Table<int>;
  delete ht;  // if you did ht, it still crashes

Upvotes: 2

dchhetri
dchhetri

Reputation: 7136

Only use "delete[]" when allocated via "new []". Only use "delete" when allocated via "new". In any other *case, don't delete the object. In your case, h_table is on stack, so the OS will take care of that.

Upvotes: 0

Related Questions