Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
189 views
in Technique[技术] by (71.8m points)

Double free or corruption (!prev) error in C

I'm getting the double free or corruption (!prev) error while implementing the following function on an online judge.

void nextPermutation(int* A, int n1) 
{
    int i    = 0;
    int tmp  = 0;
    int flag = 0;
    int ret  = 0;

    if(n1 == 1)
        return A[0];

    for(i = n1; i > 0; i--)
    {
        if(flag == 0)
        {
            if(A[i] > A[i - 1])
            {
                tmp      = A[i];
                A[i]     = A[i - 1];
                A[i - 1] = tmp;
                flag     = 1;
                ret      = i;
                break;
            }
        }
    }

    for(i = ret; i < n1 - 1; i++)
    {
        if(A[i] > A[i + 1])
            tmp = A[i];

        A[i]     = A[i + 1];
        A[i + 1] = tmp;
    }
}

However, when I test the code using custom inputs, it works fine. Could anyone tell me why does this happen?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

What is the size of int* A in this code. I think in the first for loop you need to initialize i with (n1-1).

for(i=(n1-1);i>0;i--)

The condition of i>0 seems to be fine since A[i-1] is being evaluated in loop.

I think you need to assign memory to int* using malloc. Also, as I stated above in the comment you can not return A[0];


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...