after delete(3):
1 2 4 5 6 7 |
after insert(3):
1 2 3 4 5 6 7 |
after delete(2):
1 3 4 5 6 7 |
The memory leaks occur because none of the strings generated in the outer while-loop are discarded after they have been output by the printf() statement.
To fix this, extendprintf("%s\n", reverse); |
to
printf("%s\n", reverse); free(reverse); |
if (argc==2 || sscanf(argv[1], "%d", &val)) { |
is incorrect. If exactly one command line argument is provided, due to the incorrect || operator in the condition, the sscanf() statement will not be executed. If no command line argument is given, the sscanf() instruction will read argv[1], which results in a segmentation fault. This can be corrected as follows:
if (argc==2 && sscanf(argv[1], "%d", &val)) { |
The second bug is that
int toss = random()%36; |
generates numbers between 0 and 35 only. This can be corrected as follows:
int toss = random()%37; |
To set the command line argument as the seed for the random number generator
#include <stdio.h> #include <stdlib.h> #define ROUNDS 10 int main(int argc, char **argv) { int val; if (argc==2 || sscanf(argv[1], "%d", &val)) { srandom(val); int i; for (i=0; i<ROUNDS; i++) { int toss = random()%38; // toss = 0 ... 36, 37 if (toss < 37) { printf("Winning number: %2d\n", toss); } else { printf("Winning number: 00\n"); // 37 encodes double zero } } } return EXIT_SUCCESS; } |