Asfaloth
Asfaloth

Reputation: 23

Dynamically Allocated Array of a Class

I've declared

private:
    Comment *commentArray;
    int arrSize;

in the header for the class in which it is used, called CommentManager. These are initialized in the constructer, as follows:

arrSize = 1;
commentArray = new Comment[arrSize];

If I'm understanding this correctly, this should create an "array" of one Comment. Then I set up the core function of this class:

void CommentManager::addComment(QString commText, int start, int end)
{
    Comment *saveArray;

    saveArray = new Comment[arrSize + 1];

    for (int i = 0; i < arrSize; i++)
        saveArray[i] = commentArray[i];

    delete[] commentArray;

    commentArray = saveArray;

    arrSize += 1;

This should enlarge the size of commentArray by one. Then I want to add the comment data, which is done through a function declared in Comment:

Header:

private:
    QString comment;
    int startPosition;
    int endPosition;

Function:

void Comment::setComment(QString comm,int newStartPos, int newEndPos)
{
    comment = comm;
    startPosition = newStartPos;
    endPosition = newEndPos;
}

I call this function as follows:

    commentArray[arrSize].setComment(commText,start,end);

This results in a segfault: according to the debugger 'comment' doesn't exist. As a result, I attempted to initialize the individual comment(s) in commentArray, but the compiler wouldn't compile that. I'm not sure what's gone wrong here, and any help would be much appreciated.

Upvotes: 2

Views: 838

Answers (2)

Praetorian
Praetorian

Reputation: 109089

commentArray[arrSize].setComment(commText,start,end);

is always going to refer to an element that doesn't exist because you're pointing to one past the number of elements in the array. The statement should be

commentArray[arrSize-1].setComment(commText,start,end);

Also, instead of manually managing an array of objects, you should probably use a container class. If you can use boost, take a look at boost::ptr_vector. If not, consider using one of the following:

std::vector<std::unique_ptr<Comment> > commentArray;

or

std::vector<std::shared_ptr<Comment> > commentArray;

Upvotes: 3

Valmond
Valmond

Reputation: 2959

 commentArray[arrSize].setComment(commText,start,end);

arrsize is one step too much.

An array with say size 10 is indexed from 0 to 9, using 10 will be out of bound.

Upvotes: 4

Related Questions