user3610400
user3610400

Reputation: 11

Segmentation Fault 11 during Runtime in C, using gcc to compile

I've been pulling my hair out over a block of code that I can't figure out how to fix, or even what's causing it to blow up in my face. I've been searching this site for people with similar problems, but I can't find one that's exactly like mine, and... well I'm just completely stumped.

int main() { 
    numOfTerms = 0;

    /*Getting length of sequence from user.*/

    printf("How many terms are in the sequence? ");

    scanf("%i", &numOfTerms);

    int terms[numOfTerms-1];

    /*Filling array with terms of the sequence, dictated by user.*/

    int integerChoice = 0;


    for (int i = 1; i < numOfTerms; ++i) {
        printf("Enter an integer: ");
        scanf("%d", &integerChoice);
        terms[i-1] = integerChoice;
    }
...

I don't have any trouble with the compilation, no warnings, no worries. But when I'm testing the program to make sure it works, I always reach the "Enter an integer: " prompt, and give it an integer only to be slapped in the face with "Segmentation fault: 11."

If it isn't already obvious, I'm... pretty new at this. I know (or at least I think know) what a segfault is. It's when your program swells up in terms of the amount of memory it uses to the point where it has to crash... right?

So why is that happening here? I already get past the point of allocating an array... which is where I'd assume the mistake is if a segmentation fault is this "ballooning" kind of problem. But no, it's happening at the lines that I suspect the least:

scanf("%d", &integerChoice);
terms[i-1] = integerChoice;

... Can anyone explain what's going on, and how I can fix it?

Upvotes: 1

Views: 332

Answers (1)

Mike
Mike

Reputation: 3732

Here is a version that works:

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

int main()
{
    int numOfTerms = 0;

    /*Getting length of sequence from user.*/

    printf("How many terms are in the sequence? ");

    scanf("%i", &numOfTerms);

    int *terms = malloc(numOfTerms * sizeof(int)); // OR   int terms[numofTerms];

    /*Filling array with terms of the sequence, dictated by user.*/

    int integerChoice = 0;

    for (int i = 1; i <= numOfTerms; ++i) {
        printf("Enter an integer: ");
        scanf("%d", &integerChoice);
        terms[i-1] = integerChoice;
    }
    return 0;
}

Note:

  • The missing 'int' declaration of numOfTerms
  • The corrected dynamically sized memory allocation for the array of terms
  • The for loop stopped early (you need to use <= size if using a one-relative index)

Upvotes: 1

Related Questions