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)
};
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With