user14681827
user14681827

Reputation: 153

Unsigned long long int as an array index in C on a very big array

I need a very big array to represent a series of points. To be more exact I need 256 * UINT_MAX points that have x and y values between 0 and 1. What I've tried so far is this but when I try to access array[i] my program crashes. What I can use to iterate through that array and to allocate that memory? Thank you!

unsigned long long int N = (unsigned long long int) 256 * (unsigned long long int) UINT_MAX;
float** array = (float**) malloc( N * sizeof(float*));
    
for(unsigned long long int i = 0; i < N; i++)
{
      array[i] = (float*)malloc(2 * sizeof(float));
      printf("Allocated");
      array[i][0] = (float) rand() / RAND_MAX;
      array[i][1] = (float) rand() / RAND_MAX;
        
}

Upvotes: 0

Views: 885

Answers (2)

John Bode
John Bode

Reputation: 123508

Assuming you're on a 64-bit platform, then it's likely that

        UINT_MAX == 4294967295
sizeof (float *) == 8

so you are trying to allocate 8 terabytes of memory in one chunk, which is almost certainly failing. Check the return value of malloc to make sure it isn't NULL.

Why do you think you need to allocate that large an array? What kind of data are you trying to model?

Upvotes: 1

J&#233;r&#244;me Richard
J&#233;r&#244;me Richard

Reputation: 50643

Your programs crashes because you try to allocate a HUGE amount of memory you likely do not have (without checking the result of malloc is NULL). Indeed, UINT_MAX is close to 4e9 on many mainstream system and so you try to allocate at least 8 * 256 * 4e9 = 8 TB of memory (without taking into account allocation in the loop that will be insanely slow)!

Upvotes: 2

Related Questions