Program Keeps Crashing

Apr 19, 2013 at 4:06pm
Hello! I'm doing a programming exercise to

a. Create an integer array of size 10 using malloc and populate it with random numbers
between 500 & 1000.
b. Create another integer array of size 20 using calloc and populate it with random
numbers between 1000 & 2000..

I've gotten it to work, but about 1 out of any 3 times the program crashes. Is there any way to fix this?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
  #include <stdio.h>
#include <stdlib.h>
#include <time.h>

main()

{
 
srand((unsigned)time(NULL));
    
int *numbers;      
int *numbers2;
int *combine;

numbers =(int *) malloc(10*sizeof(int));
numbers2 = (int*) calloc(20,sizeof(int));

printf("Here is the list of numbers made with malloc!\n\n");

for(int x=0; x<10; x++)
 {
   numbers[x]=(rand()%500)+501; 
   printf("  Malloc Number #%d:  %d\n", x+1, numbers[x]);
 }
 
printf("\n\n");

printf("Here is the list of numbers made with calloc!\n\n");

for(int y=0; y<20; y++)
 {
   numbers[y]=(rand()%1000)+1001; 
   printf("  Calloc Number #%d:  %d\n", y+1, numbers[y]);
 }
 
printf("\n\n"); 

system("PAUSE");
      
}
Last edited on Apr 19, 2013 at 4:08pm
Apr 19, 2013 at 4:18pm
In the second loop you are using array numbers but you need to use numbers2. numbers array holds only 10 integers so in the second loop you iterate out of bounds.

1
2
3
4
5
for(int y=0; y<20; y++)
 {
   numbers2[y]=(rand()%1000)+1001; // fixed
   printf("  Calloc Number #%d:  %d\n", y+1, numbers2[y]); // and here
 }
Apr 19, 2013 at 4:26pm
Thank you! I did the edits and ran the program and it's working expertly now. C:
Topic archived. No new replies allowed.