dimanche 31 mai 2015

Test class destructor for pointer being allocated?

So I am having a problem with my code. I want to pass a value from my array of pointers to a function so the original object is not 'disturbed' (my code works perfectly fine if I pass the reference; I just am just trying to do it a different way as a learning exercise). After the implementation returns, I get an error:

"error for object 0x100105790: pointer being freed was not allocated *** set a breakpoint in malloc_error_break to debug".

I know this is because as the value goes out of scope upon the function's return, the destructor is called for the object but my destructor assumes a pointer that was allocated, thus the error. I was curious if there was a way to test if the genome was already allocated or not. If not I would do something else for the destructor? Is this even a problem worth bothering about since I already have it working by passing in the reference? The function is not actually destructive; I just have a desire to do some tricks. I don't like taking the easy way out.

//class destructor for int genome[]
Organism::~Organism() {
    //cout << "Deleting this: " << this << endl;
    if (this->genome != NULL) {
         delete [] this->genome;
    }
}

//function definition
Organism* reproduce(Organism, Organism);

//function call in main()
offspring.push_back(reproduce(*reproduceable[i], *reproduceable[i+1]));

//function implementation
Organism* reproduce(Organism a, Organism b) {
    int genome[4];

    //randomly decide on where to split parent genomes
    int split = rand() % 5;
    for (int i = 0; i < a.get_size(); i++) {
        if (i < split) {
            genome[i] = a.get_genome()[i];
        } else {
            genome[i] = b.get_genome()[i];
        }
    }
    //now cause random mutation in 2% of the population
    if ((rand() % 100 + 1) <= 2) {
        int rand_index = rand() % 5;
        int mutation = rand() % 6 + 1;

        genome[rand_index] = mutation;
    }

    Organism *child = new Organism(4, genome); //need to add genome
    return child;
}

Aucun commentaire:

Enregistrer un commentaire