Hey, I'm getting an error when deleting a dynamic array in the deconstructor of an object.
This is the error:
*** Error in `./a.out': free(): invalid next size (fast): 0x00000000015d24d0 ***
I've created a dynamic array which is meant to hold pointers to other objects.
Let me just put some of the code down.
This is the object giving me trouble
1 2 3 4 5 6 7 8 9 10 11
cinema::cinema(int maxMovies, int max_capacity){
number_of_movies = maxMovies;
movie_list = new movie*[number_of_movies];
}
void cinema::add_movie(movie *m){
movie_list[current_movie] = m;
current_movie++;
}
cinema::~cinema(){
delete[] movie_list;
}
This is in the main function
1 2 3 4 5 6 7 8 9 10 11 12 13
movie m(name,classification,critic_rating);
movies[i]=&m;
}
for(int i = 0; i<number_of_cinemas; i++){
cinema c(number_of_movies, cinema_capacity);
//populate movie list
for(int j = 0; j<number_of_movies;j++){
int random = rand()%number_of_movies;
cout<<random<<endl;
c.add_movie(movies[random]);
}
}
If I don't add any movie objects to the list in my main, then it doesn't crash. If I don't delete the array in the deconstructor, then it doesn't crash. I was thinking that there might be a problem with the fact that the same pointers are going in multiple cinema objects. They might then be getting deleted by one deconstructor, and then the next one has issues deleting, because the array might be full of null objects. Just a theory though. I'm kinda stumped on it. Any help would be awesome. Thanks.
movie m(name,classification,critic_rating);
movies[i]=&m;
} // <-- m goes out of scope here.
// That means it will no longer exist. movies[i] is now a "dangling pointer" meaning
// it points to an object that no longer exist. You cannot safely use this pointer
// after this.
You might want to store actual movie objects (not pointers) in the array. This means you will have to copy the objects into place (or construct them in place). If you use pointers you probably want to allocate the objects using new so that they stay alive until you explicitly destroy them using delete.
Note that delete[] movie_list; only destroys the list of pointers. It does not destroy the objects that the pointers point to.