### Program Keeps Crashing

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?

 ``1234567891011121314151617181920212223242526272829303132333435363738394041`` `````` #include #include #include 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
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.

 ``12345`` ``````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 }``````
Thank you! I did the edits and ran the program and it's working expertly now. C:
Topic archived. No new replies allowed.