Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
    }
}
like image 871
idigyourpast Avatar asked Dec 07 '22 08:12

idigyourpast


2 Answers

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;
    }
}
like image 75
chrisaycock Avatar answered Dec 09 '22 15:12

chrisaycock


Your malloc call requests 16 gigabytes of memory from the system. If you don't have that much free virtual memory, or if you are running on any 32-bit system, the call will fail. If you don't check for the failure of malloc, as your code doesn't, the array will be NULL and any subsequent access to its elements will cause a segmentation fault.

If you really need to work with an array that large, you will either need to get a 64-bit system with a lot of memory, or rewrite your program to work with a smaller working set, and persist the rest to disk.

like image 33
user4815162342 Avatar answered Dec 09 '22 15:12

user4815162342