Search code examples
c++csegmentation-faultsieve-of-eratosthenes

Why am I getting segfault from this unsigned int?


I'm trying to initialize an integer array and set all elements to 1. I need the array to have an upper bound of 4294967295, or the maximum number possible for a 32-bit unsigned int.

This seems like a trivial task to me, and it should be, but I am running into segfault. I can run the for loop empty and it seems to work fine (albeit slowly, but it's processing nearly 4.3 billion numbers so I won't complain). The problem seems to show up when I try to perform any kind of action within the loop. The instruction I have below - primeArray[i] = 1; - causes the segfault error. As best as I can tell, this shouldn't cause me to overrun the array. If I comment out that line, no segfault.

It's late and my tired eyes are probably just missing something simple, but I could use another pair.

Here's what I've got:

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

Solution

  • Check the return code from malloc() to make sure the array was actually allocated. I suspect that the following test would fail:

    int *primeArray = (int*) malloc(numberOfPrimes * sizeof(int));
    
    if (primeArray != NULL) {  /* check that array was allocated */
        for (i = 0; i < numberOfPrimes; ++i) {
            primeArray[i] = 1;
        }
    }