Search code examples
c++dynamic-arrays

Define a dynamic array in a function, then return the array element. How to release array's memory?


double fibonacci(int n, double **p)
{
  if(n == 0)
    return n;
  (*p) = new double[n];
  memset(*p, 0, n);
  (*p)[0] = 0;
  (*p)[1] = 1;
  for(int i = 2; i <= n; i++)
    (*p)[i] = (*p)[i-1] + (*p)[i-2];
  return (*p)[n];
}
int main()
{
  double *p = NULL;
  cout << fibonacci(1, &p) << endl;
  delete []p;
}

the output is:

*** Error in `/home/tardis/codeblocks/test/bin/Debug/test': free(): invalid next
 size (fast): 0x08932008 ***
Aborted (core dumped)
Process returned 134 (0x86)   execution time : 0.185 s

I define a dynamic array in Fibonacci. I want to delete it in function main. Why I can't delete it? I tried to fix this error, but I failed.


Solution

  • You're allocated an array of size 1, but with (*p)p[0] = 0; (*p)p[1] = 1;

    you're writing beyond the end of the array. You're corrupting something, it maybe the heap info the array you are free'ing. I can't reproduce the the exact issue, but something pretty close. Adding guard to make sure that (*p)[x] is only assigned to when x

    It doesn't give correct results, but that's not the main issue atm.