Hi, I come across a task while trying to improve my C++ skills. It compiled fine and gives me the correct result. But when executing with a large data, it gives me std::bad_alloc, which I think is from a memory leak? So any idea how to overcome or what I can do?
This is the function I trying to call (which no modification is allowed)
1 2 3 4 5 6 7 8 9 10 11
std::vector<int> *result = new std::vector<int>();
for (int i = 0, size = std::rand(); i < size; i++)
The task is to call the function which will create some vector<int> and I need to sum them up and determine the total is an odd or even number. Below is my code: I'm stuck on how to fix that memory leak. Thanks for the help.
Thanks for the answer. But the rand() function is being called in CreateRandomizedIntVector function which I not suppose to modify.
My own code didn't use it, so I can assume its the line where I called std::vector<int>* test = CreateRandomizedIntVector();
Is there a way to overcome this without changing the CreateRandomizedIntVector function? Don't think declare or assign a larger memory allocation will help? Does that mean I have to do something with the pointer part?
That line isn't really giving you trouble. I ran your code in a debugger and I found that the program crashes at the last iteration of the while loop because test->empty() incorrectly returns true.
At least in Visual Studio, whaat makes it crash is a write access violation.
EDIT: I'm an idiot, I didn't notice you used delete instead of delete (notice the missing operator ).
What you're trying to accomplish is deleting a pointer to a vector, not a pointer to an array of vectors. The two things are actually very different.
Thank for the reply. Just so we on the same page, I run some srand() with a seed before calling the CreateRandomizedIntVector().
This will help me get some idea on how large the rand() will be, hence I can declare the vector size to use before calling the method. Am I getting this correct? But then, why are we picking the rand value to be less than 10000? to get a max value it will assigns, shouldn't we be finding greater than 10000?
The CreateRandomizedIntVector() has obviously been written with the assumption that rand() has a very limited range, so the problem that you are facing is not what the original author intended. The solution that Cubbi proposed is a hack that you should never need to do in real code. You can of course try to solve it anyway as a fun exercise but in general I would say that such a buggy function should either be fixed, or not be used at all.