Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Segmentation fault occurs when generating large amounts of doubles with rand() in C

According to gdb this line causes a segmentation fault

((double) rand()/(double) (RAND_MAX)) * (r*2)

but this is completely fine

((float) rand()/(float) (RAND_MAX)) * (r*2)

I can make do with floats, but this bugs me. Am I doing something wrong or is rand() incapable of dealing with doubles.

Notice that in the context of upper example all occurrences of float were changed to double.

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

struct cord {
    /* float or double */
    float x;
    float y;
};

int main() {
    float r = 3.0;
    int amount = 1000000;
    struct cord cords[amount];

    srand(time(NULL));
    for (int i = 0; i < amount; i++) {

        cords[i] = (struct cord) {
            /* Segfault occurs when (float) is replaced with (double) */
            ((float) rand()/(float) (RAND_MAX)) * (r*2),
            ((float) rand()/(float) (RAND_MAX)) * (r*2)
        };

    }
}
like image 222
Ritielko Avatar asked Oct 13 '25 04:10

Ritielko


1 Answers

At the time the segfault occurs, there is no more stack space to allocate the new double value. The location of the next double would be at an illegal (out-of-bounds) memory address, hence the segfault.

The reason why your code does not segfault for float is because floats are single-precision and usually requires half the number of bytes (usually 4B) to store compared to a double (usually 8B). Your code still have sufficient space to store all the floats.

like image 136
Ṃųỻịgǻňạcểơửṩ Avatar answered Oct 14 '25 19:10

Ṃųỻịgǻňạcểơửṩ