Search code examples
csegmentation-faultunsigned-integerinteger-arithmetic

Getting segmentation fault after performing arithmetic on unsigned int


The code is given below. I'm getting segmentation fault can't understand why. I think it's because of the arithmetic I'm doing on the variables t and k(both are unsigned int), can anyone explain why this segmentation fault is occurring.

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>

int main() {

    unsigned int n,k,q,i,t;
    scanf("%u %u %u",&n,&k,&q);
    unsigned int a[n];
    for(i=0;i<n;i++)
    {
        scanf("%u",&a[i]);
    }
    for(i=0;i<q;i++)
    {
        scanf("%u",&t);
        if(t-k>0)
            printf("%u\n",a[t-k]);
        else
            printf("%u\n",a[t-k+n]);
    }   
    return 0;
}

Solution

  • I think that the problem is related to this if statement

        if(t-k>0)
            printf("%u\n",a[t-k]);
    

    As t and k are both unsigned integers then the result of t-k is always non-negative even if t is less than k. But the result can give a wong index for the array element a[t-k]

    The else statement

        else
            printf("%u\n",a[t-k+n]);
    

    is executed only when t is equal to k.:) But in this case the index of tha array t-k+n will be equal to n and refer to beyind the array.

    printf("%u\n",a[t-k+n]);
    

    Take into account that the condotion in the if statement

    if(t-k>0)
    

    could be substituted for

    if ( t > k )
    

    But in any case you should check that the resulted index of the outputted element will be valid.