1

I'm writing a backtracking problem for homework, and all the code works except for my delete[] at the end.

/*Assg4.cc*/
int main()
{
    //removed irrelevant code - see pastebin links if needed

    void *data = &datavector;
    bool finished = false;
    bool* continuance = &finished;
    int *a = new int[n+1];
    for(int i=0; i<n; i++)
    {
        a[i] = NULL;
    }

    delete []a;
    delete continuance;

return 0;
}

I get the following error:

*** glibc detected *** ./Assg4: free(): invalid pointer: 0xbfc7098f ***

The function backtrack() merely fills the contents of the array a[] at some point, it doesn't delete, expand, or shrink the array in any way. I know the problem is with the deletes at the end, because when I comment them out I get no error (and the result of all computations is correct). What am I doing wrong?

Pastebin full files:

Assg4.cc

backtrack.cc & backtrack.h

4

2 回答 2

5

Pretty sure your error is actually here:

delete continuance;

You're trying to delete something allocated on the stack, since continuance points to finished, which is allocated on the stack (without a call to new). Items on the stack will be destroyed automatically when they go out of scope, so you don't have to worry about deleting continuance.

See: What and where are the stack and heap

于 2013-03-30T05:38:47.143 回答
3
bool finished = false;
bool* continuance = &finished;

delete continuance;

You are calling delete on a pointer which is not allocated using new. This is causing an Undefined Behavior.
finished is a automatic/local variable which is autmatically destroyed once the scope { } in which it is declared ends.

The rule is simple:

Don't call delete unless you called new.

于 2013-03-30T05:39:35.300 回答