Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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];


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...