产生 "zsh分段故障 "的C代码

问题描述 投票:0回答:1

我写了一个简单的脚本来计算质数,但是当我编译和运行它时,我得到了这个错误,而且总是在106747之后。

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

这就是代码。

#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);
}

有人知道我的错误在哪里吗?我也不知道。

我正在运行Mac OS Catalina (x86_64-apple-darwin19.0)。

c segmentation-fault zsh primes
1个回答
1
投票

制作 Len 全局变量,并改变 isPrime 到这一点。

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;
}

你会发现,在某些时候 i 大于 Len意思是你正在访问的是 Primes 数组越界,导致未定义的行为。

© www.soinside.com 2019 - 2024. All rights reserved.