Hi guys. In the code below, I am making a class 'agent' and then making an array of agents in function 'main'. This throws the error given below. In the function 'main', if I remove "delete  my_agents", then code runs fine. So my guess is that the issue is related to "delete  ..." in the class. It will be much appreciated if you could point out the source of error. Please note that I have implemented the rule of three in the class and have given the relevant parts of the code.
//This function reads parameter from a file - it works fine.
read_par( n_agents, n_stocks, n_memory, n_stratagies,);
agent * my_agents;
my_agents = new agent [n_agents];
//Stuff here - works fine.
delete  my_agents;
Usually when delete craps out it's because the allocated memory has been corrupted. This happens when you step out of bounds of the allocated array. So the problem is likely in how you're accessing my_agents. Double check to make sure you're never going out of bounds when you access it.
Although... is there a reason you can't use vectors? This would be a lot simpler if you could.
I'm not seeing any issues either. Do you mind posting the code that deals with my_agents? The issue is likely there, or with one of the several dynamic arrays you have in the agent class. There's a lot of allocating and deleting going on, I'd make sure you're not deleting already deleted memory when the destructor gets called.
I have check again but so far, the problem remains the same.
Can you post more code? There's obviously a bug somewhere, and I don't think it's in the code you posted. Without seeing more code I won't be able to diagnose further.
To save the final data, I am using a package which takes array as input. So I don't want to use vectors here.
Vectors are stored as linear arrays (memory is guaranteed to be contiguous with vectors). So you can pass a vector's data to a function which is expecting an array.
1 2 3 4 5 6 7 8 9 10 11 12 13
void func_that_takes_array(int* ar, int size)
func_that_takes_array( foo.data(), foo.size() ); // OK (C++11)
func_that_takes_array( &foo, foo.size() ); // OK (if your compiler doesn't support C++11)
So unless the routines you're communicating with are actually resizing the arrays (doubtful), you can still use a vector. Which would not only greatly simplify this, but also... in debug builds, vectors often do bounds checking, so the bug would be immediately exposed.
Thank you Disch and ResidentBiscuit! You were right and I managed to find the error in other part of the code. Affirmation on the posted code was necessary to be sceptical about the other piece, particularly when that seemed to work fine! Also, thanks for tips on using vectors.
Topic archived. No new replies allowed.
You are using a version without Ads of this website. Please, consider donating: