I populate a randomly sized array with random numbers. The random numbers should not have a value greater than 1000. Mostly it works fine, but occasionally when I run the program the last memory location will show a number higher than 1000. What am I doing wrong? Some kind of NULL terminator I am missing? I am Novice level.
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#define Random(high, low) (rand() % (high - low)) + low
int * GetArray(int);
int main()
{
srand(time(NULL));
int num = Random(15, 5);
GetArray(num);
return 0;
}
int * GetArray(int size){
int* ptr = (int*)malloc(size * sizeof(int));
for(int x = 0;x < size;x++){
ptr[x] = Random(1000,1);
}
printf(" Forward: ");
for (int x=0; x<=size; x++){
printf("a[%d]=%d ",x, ptr[x]);
}
printf("\r\nBackward: ");
for (int x=size; x >=0 ; x--){
printf("a[%d]=%d ",x, ptr[x]);
}
return ptr;
}