How to handle passed runtime arrays between classes in C ++

Right now I have a simple class that handles parsing XML files into ints that are useful to me. It looks something like this:

int* DataParser::getInts(){
    *objectNumbers = new int[getSize()];
    for (int i=0;i<getSize();i++){
            objectNumbers[i]=activeNode->GetNextChild()->GetContent();
    }
    return objectNumbers;
 }

      

In the main part of the program, I get this by doing:

int* numbers= data->getInts();
///Do things to numbers[]
delete numbers;

      

Everything works fine until the delete command completes. What is the correct way to do this?

+1


a source to share


5 answers


Part of the problem is that you are not pairing new [] with delete []. This is probably not the root of your mistake, but you should enjoy it.

The error is almost certainly related to the code you left without comment. Can you add some more context so we can see what you are doing with the meaning of the numbers?



In general, I find it a lot easier to use a vector for this type of problem. It takes memory management out of the equation and has the added benefit of storing size with dynamic memory.

void DataParser::getInts(std::vector<int>& objectNumbers){
    for (int i=0;i<getSize();i++){
      objectNumbers.push_back(activeNode->GetNextChild()->GetContent());
    }
 }

...
std::vector<int> numbers;
data.getInts(numbers);

      

+9


a source


You need

delete [] numbers;

      

Rules are when you

ptr = new Type[...];

      

make sure that you



delete [] ptr;

      

instead of the usual

delete ptr;

      

which will result in undefined behavior (thanks to Neil Butterworth) and is intended to remove a single instance where ptr points to, not an array.

+3


a source


Next line:

 *objectNumbers = new int[getSize()];

      

What is he doing? If you are returning objectNumbers

it is a pointer to int

, and you should really do:

 objectNumbers = new int[getSize()];

      

Anyway, C ++ gives you collections ( vector

, list

etc.) - I would use one of them instead of a simple array. As noted elsewhere, it's important to match yours new

with delete

and a new []

with delete []

.

Passing arrays around is not bad design - you make the implementation public. Try passing iterators to the beginning and end of the array / collection / sequence int

and then follow the STL project.

+2


a source


just use std :: vector;

std::vector<int> DataParser::getInts(){
    std::vector<int> objectNumbers(getSize());
    for (int i=0;i<getSize();i++){
            objectNumbers[i]=activeNode->GetNextChild()->GetContent();
    }
    return objectNumbers;
 }

      

+2


a source


You will quickly run into service issues and problems. Consider using std :: vector, this is the correct way to do it.

+1


a source







All Articles