dunlop
dunlop

Reputation: 71

How to get array of random doubles in C?

I want to generate an array with random doubles but get an "Segmentation Fault" instead of the result. When I use the same code but replace double with float, everything works. How is that? Code below works:

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

int N = 1048576;

int main(void) {
    srand(time(NULL));

    float B[N];

    for (int i = 0; i < N; i++) {
        B[i] = (float)rand() / RAND_MAX;
    }

    printf("B[0]=%lf\n", B[0]);

    return 0;
}

And code below gives me segmentation fault

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

int N = 1048576;

int main(void) {
    srand(time(NULL));

    double B[N];

    for (int i = 0; i < N; i++) {
        B[i] = (double)rand() / RAND_MAX;
    }

    printf("B[0]=%lf\n", B[0]);

    return 0;
}

I'm a noob in C, so any detailed explanation would be appreciated.

Upvotes: 1

Views: 490

Answers (3)

visu
visu

Reputation: 173

You want to allocate the memory with malloc instead of using the stack.

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

int main(void) {
  srand(time(NULL));

  size_t N = 1234567ull;
  double *array = malloc(sizeof(double) * N);

  if (array == NULL) {
      perror("array allocation");
      return EXIT_FAILURE;
  }
  
  for (size_t i = 0ull; i < N; i++) {
    array[i] = (double) rand() / RAND_MAX;
  }

  printf("%f\n", array[0]);
  free(array);
  return EXIT_SUCCESS;
}

Upvotes: 3

chqrlie
chqrlie

Reputation: 145277

You define an array float B[N]; with automatic storage that is quite large (4MB), you are lucky the stack is large enough on your system to accommodate such an object. Conversely changing the type to double also doubles the size of this local object, which seems definitely too large to allocate on the stack, invoking undefined behavior as you observe.

It is recommended to allocate large arrays from the heap using malloc or calloc.

Here is a modified version:

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

size_t N = 1048576;

int main(void) {
    srand(time(NULL));

    double *B = malloc(sizeof(*B) * N);
    if (B == NULL) {
        fprintf(stderr, "cannot allocate B\n");
        return 1;
    }

    for (size_t i = 0; i < N; i++) {
        B[i] = (double)rand() / RAND_MAX;
    }

    printf("B[0]=%f\n", B[0]);

    free(B);

    return 0;
}

Upvotes: 2

Vlad from Moscow
Vlad from Moscow

Reputation: 311088

The array has automatic storage duration and is too big for allocation with the automatic storage duration.

Either declare it in the file scope or with the storage specifier static within the function main to make it with static storage duration. Or allocate the array dynamically.

Upvotes: 0

Related Questions