Home > Software engineering >  Can anyone make me understand why visual studio is giving me this warning for my c code?
Can anyone make me understand why visual studio is giving me this warning for my c code?

Time:04-21

I don't understand why the code has this warning:

C6385: Reading invalid data from 'arr': the readable size is '160' bytes, but '200' bytes may be read.

This is a program to randomize numbers from the size of the string array and using these numbers to access elements within string array, 'arr'.

Here is the C code:

#include <iostream>
#include<time.h>
#include<stdlib.h>

using namespace std;

int main()
{
   string arr[] = {"hey","music","ola","dang"};
   int size = sizeof(arr) / sizeof(arr[0]);

    int random;

    srand(time(0));
    for (int  i = 1; i <= size; i  )
    {
        random = rand() % ((size 1-1) 1);
        cout << random << "\t" << arr[random] << endl;
        

    }
    cout << endl;}

CodePudding user response:

Indexing of arrays in C starts from 0 instead of 1. This means that we can only safely access the elements with indices from 0 upto n - 1 where n is the number of elements in the array. Thus in your example, we can only safely access elements with index: 0, 1, 2 and 3. And if we use any other positive integer(that is greater than 3), then the program will have undefined behavior.

To solve this make sure that random always ranges from 0 upto 3 which you can do by changing random = rand() % ((size 1-1) 1); to:

random = rand() % (size);

So the modified code looks like:

int main()
{
   string arr[] = {"hey","music","ola","dang"};
   int size = sizeof(arr) / sizeof(arr[0]);

    int random;
    
    srand(time(0));
    for (int  i = 0; i < size; i  )//note the indexing starts from 0 
    {
        random = rand() % ((size)); //changed this 
        cout << random << "\t" << arr[random] << endl;
        

    }
    cout << endl;
    
}

Demo

  •  Tags:  
  • c
  • Related