Daniel Ilie
Daniel Ilie

Reputation: 127

Segmentation Fault (core dumped).. Not sure why?

Trying to learn how to code in C, getting this error.

Making a program that gets a year and figures out if it is a leap year or not then prints the result.

The error I'm getting is segmentation fault(core dumped) Really new to coding in C, not sure how to fix this and the error doesn't point to a specific line or anything. Really appreciate some advice, anything helps. Thanks!

This is my code:


int isLeap(int date){

    if(date%400 == 0){
        return 1;
    }

    if(date%4 != 0){
        return 0;
    }

    if(date%100 != 0){
        return 0;

    }

}


int year;
 int green = 0;

  while(green == 0){

     printf("Enter a year: " );
  scanf("%d", year);


  if(year < 0){
      green++;
  }

  if(isLeap(year) == 1){
      printf("Year %d is a leap year.", year);
  }
  if(isLeap(year) == 0){
      printf("Year %d is not a leap year", year);
  }
}
return 0;

} ```

Upvotes: 2

Views: 1448

Answers (1)

Lee Jenkins
Lee Jenkins

Reputation: 2470

Because you said you are new to C programming, let me elaborate a little bit on Christian Gibbons' comment above. The answer is correct, but it doesn't really explain why. Here's the comment:

scanf("%d", year); -> scanf("%d", &year);

The error Segmentation Fault (core dumped) indicates an improper use of a pointer. Or, in your case, using a non-pointer value as if it were a pointer. A pointer is a memory address. When you use a pointer, you're telling the CPU to go fetch information from (or put information into) the memory at an address. If you give the wrong address, bad things often happen.

The function scanf() requires pointers for the variables whose values are assigned from the string scan. In your case, you passed year (the current value of the year variable) instead of &year (the address of the year variable).

Don't despair. Pointers are challenging to understand at first, but stick with it and you'll get it. Here are some references where you can learn more:

Pointers:

Segmentation Fault:

Upvotes: 1

Related Questions