c++ - Define a dynamic array in a function, then return the array element. How to release array's memory? -
c++ - 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) homecoming n; (*p) = new double[n]; memset(*p, 0, n); (*p)[0] = 0; (*p)[1] = 1; for(int = 2; <= n; i++) (*p)[i] = (*p)[i-1] + (*p)[i-2]; homecoming (*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 dynamic array in fibonacci. want delete in function main. why can't delete it? I tried prepare error, failed.
you're allocated array of size 1, (*p)p[0] = 0; (*p)p[1] = 1;
you're writing beyond end of array. you're corrupting something, maybe heap info array free'ing. can't reproduce the exact issue, pretty close. adding guard create sure (*p)[x] assigned when x
it doesn't give right results, that's not main issue atm.
c++ dynamic-arrays
Comments
Post a Comment