Rashu
Rashu

Reputation: 25

whenever I run my c++ programm, my program has stopped working

I am very new in data structures and algorithm. I get stuck in my program. I could not find the reason why it happens. whenever I run, a display pop-up and show file.exe has stopped working. If you guys know the problem, please help me. And, if I have mistaken somewhere in writing, please ignore it. Because, English is not my primary language.

#include<iostream>
using namespace std;

class List{
private:
    int m_count;
    int *m_items;
public:
    int Get(int index);
    void Insert(int index, int val);
    int Search(int val);
    void Remove(int index);
};

int List::Get(int index){
    if(index < 0 || index > m_count){
        return -1;
    }
    return m_items[index];
}

void List::Insert(int index, int val){
    if(index < 0 || index > m_count){
        return;
    }
    int *OldArray = m_items;
    m_count++;
    m_items = new int[m_count];
    for(int i=0, j=0; i<m_count; i++){  
        if(index == i){
            m_items[i] = val;
        }else{
            m_items[i] = OldArray[j];
            j++;
        }
    }
    delete [] OldArray;
}

int List::Search(int val){
    for(int i=0; i<m_count; ++i){
        if(m_items[i] == val){
            return i;
        }
    }
    return -1;
}

void List::Remove(int index){
    if(index < 0 || index > m_count){
        return;
    }
    int *OldArray = m_items;
    m_count--;
    m_items = new int[m_count];
    for(int i=0, j=0; i<m_count; ++i,++j){
        if(index == j){
            j++;
        }
        m_items[i] = m_items[j];
    }
    delete [] OldArray;
}

int main(){
List list;
list.Insert(0, 1);

return 0;
}

Upvotes: 1

Views: 69

Answers (1)

MikeCAT
MikeCAT

Reputation: 75062

The member m_items is not initialized.

Calling list.Insert(0, 1); will make it execute delete [] OldArray; with an uninitialized value.

Add a constructor to initialize the members like:

List() : m_count(0), m_items(nullptr) {}

Also you should follow The Rule of Three. In other words, you should also define a copy constructor, an assignment operator, and a destructor to copy the contents of the array instead of simply copying the pointer and to avoid troubles when the objects are copied.

Upvotes: 1

Related Questions