Adi Mehrotra
Adi Mehrotra

Reputation: 150

C code generating a "zsh segmentation fault"

I wrote a simple script to calculate prime numbers but when I compile and run it, I get this error and always after 106747.

...
106727
106739
106747
zsh: segmentation fault  ./a.out 1000000

This is the code:

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

int *Primes;

int isPrime(int n) {
    int i = 0;
    int calc_to = ceil(sqrt(n));
    while (Primes[i] < calc_to) {
        if (n % Primes[i] == 0) {
            return 0;
        }
        i ++;
    }
    return 1;
}

int main(int argc, char *argv[]) {
    if (argc != 2) {
            printf("Usage: ./a.out <Find Till>");
            return 0;
    }

    int Len = 3;
    Primes = malloc(sizeof(int) * Len);
    Primes[0] = 2; Primes[1] = 3;
    printf("2\n3\n");

    int calc_to = atoi(argv[1]);
    for (int n = 4; n < calc_to; n++) {
        if (isPrime(n) == 1) {
                Primes[Len - 1] = n;
                printf("%d\n", n);
                Primes = realloc(Primes, sizeof(int) * Len);
                Len ++;
            }
        }
    free(Primes);
}

Does anyone know what my mistake is? I have no clue.

I'm running Mac OS Catalina (x86_64-apple-darwin19.0)

Upvotes: 2

Views: 1834

Answers (1)

Jabberwocky
Jabberwocky

Reputation: 50883

Make Len a global variable and change isPrime to this:

int isPrime(int n) {
  int i = 0;
  int calc_to = ceil(sqrt(n));
  while (Primes[i] < calc_to) {
    if (i >= Len)                 // add this line
    {                             // add this line
      printf("Bummer");           // add this line
      exit(1);                    // add this line
    }                             // add this line
    if (n % Primes[i] == 0) {
      return 0;
    }
    i++;
  }
  return 1;
}

You'll notice that at some point i is greater equal than Len, meaning that you're accessing the Primes array out of bounds which leads to undefined behaviour.

Upvotes: 3

Related Questions