c - 数组超过大约 255000 int 时出现段错误

标签 c

我正在编写一个程序来查找所有小于某个数的素数。一旦我的素数列表超过大约 255000 个素数,我就会收到错误“Segmentation fault: 11”。事件监视器说我的进程只使用了 1.2MB。这是我的代码:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <sys/types.h>
#include <unistd.h>

int main(){
    int N;
    int arraySize = 1;
    int *primes = malloc(100*sizeof(int));
    int isPrime = 1;
    primes[0] = 2;
    int timesRealloc = 0;
    int availableSlots = 100;

    printf("Please enter the largest number you want checked: \n");
    scanf("%d", &N);

    int j = 0;
    int i;
    for (i = 3; i <= N; i++){ 
        j = 0;
        isPrime = 1;
        while (primes[j] <= sqrt(i)) {
            if (i%primes[j] == 0) {
                isPrime = 0;
                break;
            }
            j++;
        }
        if (isPrime == 1){
            primes[arraySize] = i;
            arraySize++;
            availableSlots = availableSlots - 1;
        }
        if (availableSlots == 0){
            timesRealloc++;
            availableSlots = 100;
            primes = realloc(primes, 100*sizeof(int));
        }
    }

    /*
    for (i = 0; i < arraySize; i++){
        printf("%d\n", primes[i]);
    }
    */
    printf("process ID is %d\n", getpid());
    printf("I found %d primes\n", arraySize);
    printf("Memory was reallocated %d times\n", timesRealloc);
    printf("The largest prime I found was %d\n", primes[(arraySize-1)]);


    return 0;
}

最佳答案

正如评论中所说,你超出了数组 primes

这里的代码修改最少,运行良好:

#include <math.h>
#include <sys/types.h>
#include <unistd.h>

int main(){
    int N;
    int arraySize = 1;
    int *primes = malloc(100*sizeof(int));
    int isPrime = 1;
    primes[0] = 2;
    int timesRealloc = 0;
    int availableSlots = 100;

    printf("Please enter the largest number you want checked: \n");
    scanf("%d", &N);

    int j = 0;
    int i;
    for (i = 3; i <= N; i++){ 
        j = 0;
        isPrime = 1;
        while (primes[j] <= sqrt(i)) {
            if (i%primes[j] == 0) {
                isPrime = 0;
                break;
            }
            j++;
        }
        if (isPrime == 1){
            primes[arraySize] = i;
            arraySize++;
         /* LINE REMOVED */
        }
        if (arraySize == availableSlots){ /* MODIFIED */
            timesRealloc++;
            availableSlots += 100; /* MODIFIED */
            primes = realloc(primes, availableSlots*sizeof(int)); /* MODIFIED */
        }
    }

    /*
    for (i = 0; i < arraySize; i++){
        printf("%d\n", primes[i]);
    }
    */
    printf("process ID is %d\n", getpid());
    printf("I found %d primes\n", arraySize);
    printf("Memory was reallocated %d times\n", timesRealloc);
    printf("The largest prime I found was %d\n", primes[(arraySize-1)]);


    return 0;
}

更改由注释指示

对我来说,arraySize 必须重命名为 numberOfPrimesavailableSlots 必须重命名为 arraySize


编译和执行:

pi@raspberrypi:/tmp $ gcc -g -pedantic -Wextra p.c -lm
pi@raspberrypi:/tmp $ ./a.out
Please enter the largest number you want checked: 
500000
process ID is 6337
I found 41538 primes
Memory was reallocated 415 times
The largest prime I found was 499979

valgrind 下执行:

pi@raspberrypi:/tmp $ valgrind ./a.out
==6354== Memcheck, a memory error detector
==6354== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==6354== Using Valgrind-3.13.0 and LibVEX; rerun with -h for copyright info
==6354== Command: ./a.out
==6354== 
1000
Please enter the largest number you want checked: 
process ID is 6354
I found 168 primes
Memory was reallocated 1 times
The largest prime I found was 997
==6354== 
==6354== HEAP SUMMARY:
==6354==     in use at exit: 800 bytes in 1 blocks
==6354==   total heap usage: 4 allocs, 3 frees, 3,248 bytes allocated
==6354== 
==6354== LEAK SUMMARY:
==6354==    definitely lost: 800 bytes in 1 blocks
==6354==    indirectly lost: 0 bytes in 0 blocks
==6354==      possibly lost: 0 bytes in 0 blocks
==6354==    still reachable: 0 bytes in 0 blocks
==6354==         suppressed: 0 bytes in 0 blocks
==6354== Rerun with --leak-check=full to see details of leaked memory
==6354== 
==6354== For counts of detected and suppressed errors, rerun with: -v
==6354== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 6 from 3)

primes 最后必须是空闲的才能没有内存泄漏


只是一个细节,但输入 1 时的行为不是预期的

pi@raspberrypi:/tmp $ ./a.out
Please enter the largest number you want checked: 
1
process ID is 6388
I found 1 primes
Memory was reallocated 0 times
The largest prime I found was 2

2 大于 1 ;-)

这是因为你强制存在 2(primes[0] = 2; 等)

关于c - 数组超过大约 255000 int 时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54873609/

相关文章:

c - 重新提交 DMA 引擎事务

c - 打开 Watcom 错误 E1127 "Type required in parameter list"

c++ - 什么是流?标准事物及其用法。

c - 我用于打印最长回文子序列的程序无法正常工作,当我运行它时,控制台窗口在接受输入后停止工作

c - Node 和C应用程序之间的进程间通信

c - 使用阵列生成错误结果的矩阵乘法

c++ - 打印 n 个空格字符 -(f)printf 格式

c - 如何比较C中的两个位值?

c - 在编译时和/或运行时检测正在运行的 Linux 发行版?

c - C中的向后递归打印