为什么我从这个unsigned int获得segfault?

idi*_*ast 4 c c++ segmentation-fault sieve-of-eratosthenes

我正在尝试初始化整数数组并将所有元素设置为1.我需要数组的上限为4294967295,或者是32位的最大数unsigned int.

这对我来说似乎是一项微不足道的任务,应该是,但我遇到了segfault.我可以运行for循环空,它似乎工作正常(尽管很慢,但它处理了近43亿个数字,所以我不会抱怨).当我尝试在循环中执行任何类型的操作时,问题似乎出现了.我在下面的指令 - primeArray[i] = 1;- 导致segfault错误.尽我所知,这不应该让我超越阵列.如果我注释掉那条线,没有segfault.

已经晚了,我疲惫的眼睛可能只是缺少一些简单的东西,但我可以使用另一双.

这是我得到的:

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <stdint.h>

#define LIMIT 0xFFFFFFFF;

int main(int argc, char const *argv[])
{
    uint32_t i;

    uint32_t numberOfPrimes = LIMIT;        // hardcoded for debugging
    int *primeArray = (int*) malloc(numberOfPrimes * sizeof(int));

    for (i = 0; i < numberOfPrimes; ++i) {
        primeArray[i] = 1;
    }
}
Run Code Online (Sandbox Code Playgroud)

chr*_*ock 10

检查返回代码malloc()以确保实际分配了数组.我怀疑以下测试会失败:

int *primeArray = (int*) malloc(numberOfPrimes * sizeof(int));

if (primeArray != NULL) {  /* check that array was allocated */
    for (i = 0; i < numberOfPrimes; ++i) {
        primeArray[i] = 1;
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 铸造malloc ?? 阅读此http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc (3认同)
  • @chrisaycock [有时是](http://stackoverflow.com/questions/7545365/why-does-this-code-segfault-on-64-bit-architecture-but-work-fine-on-32-bit)所以铸造是一个糟糕的建议. (2认同)

use*_*342 5

您的malloc呼叫从系统请求16千兆字节的内存.如果没有那么多可用虚拟内存,或者如果您在任何32位系统上运行,则呼叫将失败.如果您没有检查失败malloc,因为您的代码没有,那么数组将是,NULL并且对其元素的任何后续访问都将导致分段错误.

如果你真的需要使用一个大的数组,你需要得到一个带有大量内存的64位系统,或者重写你的程序以使用一个较小的工作集,并将其余部分保存到磁盘上.