dynamic memory alloc and recursion

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • crimsonalucard
    New Member
    • Oct 2007
    • 1

    #1

    dynamic memory alloc and recursion

    Below is a function I wrote used to evaluate the determinant of a nxn matrix. arguments are an array of the matrix values in order going from left to right jumping to the next line then going from left to right again.

    An error happens after the function recursively calls itself once and attempts to allocate dynamic memory for a sub-matrix.

    I'm not sure why this happens? Can anyone explain why an error occurs and how to correct it? Thanks.

    [code=cpp]
    double evaluate(double *mat,int dim)
    {
    //smallest case
    if(dim==2)
    {
    return mat[0]*mat[3]+mat[2]*mat[1];
    }
    //smallest case
    int b;
    double result = 0;
    //iterate through columns
    for(int j =0; j<dim; j++)
    {
    //calculate b
    if((j+2)%2==0)
    {
    b=1;
    }
    else
    {
    b=-1;
    }
    //calculate b
    //smaller matrix
    double *smaller = new double [(dim-1)*(dim-1)];//error occurs here after one recursive call
    int counter=0;
    for (int p = 0; p<dim*dim; p++)
    {
    if(dim != j)
    {
    smaller[counter]=mat[p];
    counter++;
    }
    }

    //smaller matrix
    result+=b*mat[j]*evaluate(small er, dim-1); //recursive call
    delete [] smaller;
    }
    return result;


    }
    [/code]
    Last edited by JosAH; Oct 15 '07, 07:22 PM. Reason: added [code] ... [/code] tags
  • RRick
    Recognized Expert Contributor
    • Feb 2007
    • 463

    #2
    One probem you is that after you create a smaller matrix of dim-1**2 size (line 25), you then fill it up with dim**2 entries.

    Since these values are on the stack, overwritting the stack like this can cause havoc with your program.

    Comment

    Working...