Search code examples
c++visual-c++compiler-errors

i am getting error in this code snippet , i don't know why


bool check(vector<int> &nums)
{
    int *big = &nums[0];
    int n = nums.size(), x = 0;

    for (int i = n - 2; i > -1; i--)
    {
        if (nums[i] > x)
        {
            x = nums[i];
        }
    }

    big = &x;
    if (big != &nums[n - 1])
    {
        big++;
    }
    rotate(&nums[0], big, &nums[n]);

    for (int i = 1; i < n; i++)
    {
        if (nums[i - 1] > nums[i])
            return false;
    }

    return true;
}
ERROR: AddressSanitizer: stack-buffer-underflow on address 0x7ffd698133fc at pc 0x00000034d07d bp 0x7ffd69813370 sp 0x7ffd69813368

getting this error


Solution

  • std::rotate requires that all three arguments refer to the same container. But in your code the pointer big holds the address of an unrelated variable x.

    Seems clear that you were trying to write this code

        int* big = &nums[0];
        int n=nums.size();
    
        for(int i = n-2 ; i > -1 ;i--)
        {
            if(nums[i] > *big)
            {
                big = &nums[i];
            }
        }
    

    Assigning to x from nums and then assigning to big the address of x is not the same thing at all as assigning directly to big the address of an element in nums.