Reputation: 957
This might sound like a silly question, but I couldn't find information on how to properly release memory in this case:
Assume there is a function returning a double*
(there is no other information available about this function). Assume further the following use case:
for (int i = 0; i < SIZE; i++) {
double *ptr = new double[3];
/// do something with ptr, e.g., print
// delete[] ptr;
}
How does one correctly release memory in this case, since a delete[] ptr;
placed in the comment above causes a backtrace (why?)?
Many thanks!
Upvotes: 0
Views: 108
Reputation: 724
Doing
double *ptr = new double[3];
delete[] ptr;
is quite right. So your problem must reside somewhere else. I can recommend using a debugger to check what's going on, and if you're on a linux system I would recommend trying valgrind/helgrind - it's pretty nice
Upvotes: 2
Reputation: 363497
there is no other information available about this function
Then you can't know how to release the memory. Look at the function's source code if you have it, otherwise contact its author or use a debugging tool to find out how it allocates its memory. A raw pointer simply doesn't carry the necessary information to know how to deallocate it.
As for your second, unrelated case, the delete[]
is correct so the problem must be in the "do something
" part (assuming you didn't perform tricks such as new
overloading).
Upvotes: 4