-1

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?

TofuBeer
  • 60,850
  • 18
  • 118
  • 163
Samdish Arora
  • 79
  • 1
  • 8
  • 1
    your function have void as return type and you are returning A[0] in first if condition. – Denis Jul 09 '16 at 06:05
  • 3
    In your second `for` loop, are all three assignments supposed to be part of the `if`? Since you didn't use braces, only the first line is in the `if`. – Barmar Jul 09 '16 at 06:07
  • Can you post the code where you calling from. – Denis Jul 09 '16 at 06:09
  • 1
    You never use flag, I mean you use it, but as soon as you set it you break out of the loop. So what is the point of flag? – TofuBeer Jul 09 '16 at 06:11
  • Possible duplicate of [How to track down a "double free or corruption" error](https://stackoverflow.com/questions/2902064/how-to-track-down-a-double-free-or-corruption-error) – Raedwald Dec 06 '18 at 13:30

1 Answers1

4

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

rango
  • 311
  • 1
  • 13
Denis
  • 1,219
  • 1
  • 10
  • 15