0

When I compile and run the following code using terminal commands(in linux mint sonya)

gcc -o program program.c ./program

I get a segmentation fault. When I do the same using Code::blocks IDE, I don't get any error. I am aware that segmentation fault arises when an illegal memory is accessed. What's wrong?

 #include <stdio.h>
    int main()
    {
    int t;
    scanf("%d",&t);
    for(t;t>0;t--)
        {
        int i,j,n,arr[n],sump=0,sums=0,total,ans;
        scanf("%d",&n);
        for(i=0;i<=n-1;i++) scanf("%d",&arr[i]);
        for(i=0;i<=n-1;i++,sump=0,sums=0)
                {
            for(j=0;j<=i;j++) sump=sump+arr[j];
            for(j=n-1;j>=i;j--) sums=sums+arr[j];
            if(i==0) ans=sump+sums;
            else if(ans>sump+sums) ans=sump+sums;
                }
        for(i=0;i<n;i++,sump=0,sums=0)
            {
            for(j=0;j<=i;j++) sump=sump+arr[j];
            for(j=n-1;j>=i;j--) sums=sums+arr[j];
                if(ans==sums+sump) break;
            }
        printf("%d\n",i+1);
        }

    }
bigcoder
  • 21
  • 1
  • 2

1 Answers1

7

You are declaring arr[n] without initializing the value of n. That is undefined behavior...

Leonardo Alves Machado
  • 2,747
  • 10
  • 38
  • 53
  • 4
    Pure luck! That's the nature of undefined behaviours – Chris Turner Sep 01 '17 at 15:09
  • 2
    @bigcoder Undefined behavior is just that,, it's undefined. You may get "lucky" and it works sometimes. Other times, as you've just experienced, it doesn't. I put lucky in quotes because when it works, that's really _unlucky_. You think everything is fine and suddenly your code is crashing at the most inopportune time and you don't know why. This is tagged c++ but it's a good illustration of undefined behavior: https://stackoverflow.com/questions/6441218/can-a-local-variables-memory-be-accessed-outside-its-scope/6445794#6445794 – yano Sep 01 '17 at 15:13