1

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;
}
MFT1272351
  • 11
  • 1
  • 2
    `for (int x=0; x<=size; x++` => `for (int x=0; x – pm100 Dec 11 '22 at 19:47
  • 1
    When you're printing them out, you're going past the end. Compare your `for` loop end conditions. You're going to have the same problem with your backward loop, except it will be the starting point that's off by one. – Ken White Dec 11 '22 at 19:49
  • Thanks Ken. Obvious mistake I should have caught. – MFT1272351 Dec 11 '22 at 19:52
  • 1
    @MFT1272351 Certainly you want `#define Random(high, low) (rand() % (high - low + 1)) + low` and not `#define Random(high, low) (rand() % (high - low)) + low`. – chux - Reinstate Monica Dec 11 '22 at 19:57
  • Does this answer your question? [Undefined behavior beyond the max index of an array](https://stackoverflow.com/questions/57127660/undefined-behavior-beyond-the-max-index-of-an-array) – OldProgrammer Dec 11 '22 at 19:58

1 Answers1

3

Imagine that size of your array is 5, so the first place is 0, second one is 1, third is 2, fourth is 3 and fifth is 4! So its size - 1

Thus you should write your for loop like this:

for(int x = 0; x < size; x++)

And

for(int x = size - 1; x >= 0; x--)
Ali
  • 439
  • 1
  • 4
  • 14