longnightofsolace
longnightofsolace

Reputation: 33

Unable to detect the reason for segmentation fault?

#include<stdio.h>
int main()
{
  int t;
  scanf("%d",&t);
  while(t-->0)
  {
      long int size;
      scanf("%ld",&size);
      long int size2=size*size;
      long int a[size],b[size2];
      long int i=0;
      for(i=0;i<size;i++)
      {
          scanf("%ld",&a[i]);
      }
      long int j=0;
      long int y;
      y=2*a[0];
      for(i=0;i<size;i++)
      {
          for(j=0;j<size;j++)
          {
              if(i!=0 && j!=0)
              {
                b[i*size+j]=a[i]+a[j];
                y=y^b[i*size+j];
              }
          }
      }
      printf("%ld\n",y);
  }
}  

I was solving for one of the problems on a popular Competitive Coding Websites, I wrote this code it works for most test cases I tried but, they didn't consider it as it gave them an RE(SIGSEV)->(Runtime error due to segmentation fault.), And didn't even provide with the test case where the error sneaked in, I made sure about the semantics of taking Input for data variables of different types and (Even made sure my code stays within the allowed limit of 50000 bytes.) Can somebody help me understand what is causing the segmentation fault here?

Upvotes: 2

Views: 67

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727027

This segmentation fault is caused by allocating too much automatic memory through VLA (variable-length arrays).

I made sure my code stays within the allowed limit of 50000 bytes

Large VLAs may cause undefined behavior even if your program has plenty of memory available for dynamic allocation, because they take memory from the automatic storage (commonly referred to as "stack"). The amount of automatic storage available to your program is usually a fraction of the total memory available to your process.

You can fix this problem by switching to dynamic allocation:

long int *a = malloc(sizeof(long int)*size);
long int *b = malloc(sizeof(long int)*size2);
...
free(a);
free(b);

Upvotes: 3

Related Questions