-1

I have this code and it gives me segmentation fault.

struct TRecord {
    const char * Id;
    const char * Name;
};
class CClass {
    CClass ();
    ~CClass ();
    bool Add ( const char * id, const char * name);
    TRecord ** m_record;
    int m_count;
};

CClass::CClass (void) {
    m_count = 0;
    m_record = new TRecord * [1000];
}

CClass::~CClass(void) {
    for(int i=0;i<m_count;i++){
        delete m_record[i];
    }
    delete [] m_record;
}

bool CClass::Add (const char * id, const char * name) {
    m_record[m_count] -> Id = new char[11];
    m_record[m_count] -> Name = new char[strlen(name) + 1];

    m_record[m_count] -> Id = id;
    m_record[m_count] -> Name = name;

    m_count++;
    return true;
}

If I add for example const char haha[2222]; to struct TRecord, it works. I don't understand why. Can you help me?

P.S. I can't use string.

Oswald
  • 31,254
  • 3
  • 43
  • 68

2 Answers2

1

One error is that you are not following the rule of three in your CRegister class. That often causes segfaults.

Another error is that you do not initialise your m_record[i] pointers. So you destructor may call delete[] on garbage values.

A third error is that you apparently dereference the same garbage values in CRegister::Add.

Community
  • 1
  • 1
john
  • 85,011
  • 4
  • 57
  • 81
1

Add this line as to top of you Add function declaration, It will fix your Segmentation Fault problem.

m_record[m_count] = new TRecord;

But as you can see in answers and comments, your code has many problems. Most important problem is that you have not any good plan for your garbage objects. So your code have memory leakage.

MostafaR
  • 3,547
  • 1
  • 17
  • 24