2
0

rand.c 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. #include <stdlib.h>
  2. #include <stdio.h>
  3. #include "test_helpers.h"
  4. int main(void) {
  5. // Uninitialized generator
  6. int rand_uninit = rand();
  7. printf("%d\n", rand_uninit);
  8. // Testing the reproducibility of values
  9. srand(259);
  10. int rand_seed259_1 = rand();
  11. printf("%d\n", rand_seed259_1);
  12. srand(259);
  13. int rand_seed259_2 = rand();
  14. printf("%d\n", rand_seed259_2);
  15. if (rand_seed259_1 != rand_seed259_2) {
  16. puts("rand() doesn't return reproducible values");
  17. exit(EXIT_FAILURE);
  18. }
  19. // Seed value 1 should return the same values as the ininitialized generator
  20. srand(1);
  21. int rand_seed1 = rand();
  22. printf("%d\n", rand_seed1);
  23. if (rand_uninit != rand_seed1) {
  24. puts("srand(1) doesn't work");
  25. exit(EXIT_FAILURE);
  26. }
  27. // Ensure rand_r() fails with NULL input
  28. if (rand_r(NULL) != EINVAL) {
  29. puts("rand_r(NULL) doesn't return EINVAL");
  30. exit(EXIT_FAILURE);
  31. }
  32. // Ensure rand_r() produces unique values
  33. int seed = 259;
  34. int rand_r_seed259_1 = rand_r((unsigned *)&seed);
  35. printf("%d\n", rand_r_seed259_1);
  36. int rand_r_seed259_2 = rand_r((unsigned *)&seed);
  37. printf("%d\n", rand_r_seed259_2);
  38. if (rand_r_seed259_1 == rand_r_seed259_2) {
  39. puts("rand_r() fails to produce unique values");
  40. exit(EXIT_FAILURE);
  41. }
  42. // Ensure rand_r() returns reproducible values
  43. seed = 259;
  44. int rand_r_seed259_1_2 = rand_r((unsigned *)&seed);
  45. printf("%d\n", rand_r_seed259_1_2);
  46. int rand_r_seed259_2_2 = rand_r((unsigned *)&seed);
  47. printf("%d\n", rand_r_seed259_2_2);
  48. if (rand_r_seed259_1 != rand_r_seed259_1_2
  49. || rand_r_seed259_2 != rand_r_seed259_2_2)
  50. {
  51. puts("rand_r() is not reproducible");
  52. exit(EXIT_FAILURE);
  53. }
  54. return 0;
  55. }