0

Let's say I want to implement a bag of worms. I have class Worm, which has an int attribute ID. I also have a class Bag:

class Bag{

    // pointer to a 1D array of pointers to all the worms
    Worm** population;

    // constructor
    Bag(){
        // initiate 1D population of the worms
        int N = 100;
        Worm** population = new Worm*[N];
        for (int i=0; i<N; i++){
            Worm new_worm(i);
            population[i] = &new_worm;
        }
    }
}

since N is known at the time of compilation I am not sure if the array has to be dynamically allocated?

My problem is that later in the code I would like to execute:

Bag bag();
int ID = bag.population[10]->ID;

and the code gets compiled but when I execute I get Segmentation fault: 11. I have checked (by commenting) that the problem is caused by the exact line of ID extraction.
How should I access the fields and call methods of class Worm in the bag?

2 Answers 2

3

replace Worm** population = new Worm*[N] with this->population or some stuff like this.

you are allocating local variable "population" instead of member "population" -> bag.population is still null

Sign up to request clarification or add additional context in comments.

Comments

2

Actually, I beleve that the real problem is that you're initializing the population array with the address(es) of a local variable, new_worm. I believe that it's undefined whether or not the addresses assigned to the array will even be difference or not (the initialization loop is free to use the same place on the local stack for the new_worm variable.

Although there are other ways to solve this, one is to replace the 2 lines:

        Worm new_worm(i);
        population[i] = &new_worm;

with:

        population[i] = new Worm(i);

1 Comment

Yes, I agree, the object should be created on the heap, not on the stack. This also led to a further problem where I was trying to free the memory in the destructor of Bag as well as automatically at the end of main() scope. I ended up getting an error of freeing the same memory address twice. Thanks for the additional info!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.