Anonymous
Anonymous asked in Computers & InternetProgramming & Design · 5 years ago

What does it mean by Segmentation Fault in C?

I'm trying to write a code that would print the odd elements and odd subscripts but I keep getting "Segmentation Fault" when I execute it:

#include<stdio.h>

int main(){

int sum1=0,sum2=0,i,test[10]={1,6,2,5,12,16,7,8,9,4};

if (test[i]%2 ==0)

sum1 = test[i];

if (test[i]%2 !=0)

sum2 = test[i];

printf("Sum of odd elements=%d\n",sum1);

printf("Sum of elements with odd subscripts=%d\n",sum2);

} //end of main

1 Answer

Relevance
  • 5 years ago
    Favorite Answer

    Segmentation fault means you tried to access an invalid memory address. This can happen easily in C if you use an invalid index value with an array.

    In your case, you declared i, but you didn't initialize it, so it will have some random, possibly very large or negative value.

    So when you do this:

    if (test[i]%2 ==0)

    You are using the uninitialized i variable as an index into array test. That resulted in trying to reference memory that was not part of the test array.

    You need to initialize i first. (And, you will probably want to use it as your loop variable, because you need a loop here to do the sums).

Still have questions? Get your answers by asking now.