delete array allocated in a function
May 25, 2010 at 1:41pm UTC
Hello, I have a deallocation problem :
I have several classes, and in one of these, a function is returning an array of double :
1 2 3 4 5 6 7 8 9 10
double *funtion()
{
double *a = new double [4];
a[0] = 1.
a[1] = 1.
a[2] = 1.
a[3] = 1.
return a;
}
An other function is calling the first one and uses the created array :
1 2 3 4 5 6
void function2()
{
double *b = function();
std::cout << b[0] << std::endl;
}
It seems to me that there is a memory leak there as I don't delete[] b in the end of function2, but when I try to do so I get an error message at runtime.
May 25, 2010 at 1:47pm UTC
If you don't use pointer after call function2 you can call delete into function2
1 2 3 4 5 6 7 8
void function2()
{
double *b = function();
std::cout << b[0] << std::endl;
delete [] b;
b = 0;
}
Of course if you need access after that you get crash
May 25, 2010 at 5:56pm UTC
Thanks Denis,
Well, I have this error message :
malloc: *** error for object 0x11f3e1af0: pointer being freed was not allocated
*** set a breakpoint in malloc_error_break to debug
When I try to delete the array in the end of the function2
That comes from trying to deallocate an already deallocated pointer right?
(BTW, I posted the thread twice, I'd like to delete the second post)
May 25, 2010 at 7:02pm UTC
That's odd. The code you posted should not break with this message. You clearly only free it once there. Post more code if possible please.
Topic archived. No new replies allowed.