简体   繁体   中英

How can I fix my code so I don't get a C6385 warning?

I'm having trouble with a C6385 warning in my code. I'm trying to see if two arrays will equal each other. The warning I keep getting is on the line where if(p[i] == inputGuess[j]). I have tried redoing these line but I keep getting the same warning. Does anyone know what I'm doing wrong. This is also my first time programming in C++.

#include <time.h>
#include <stdlib.h>
#include <stdio.h>
#include "Game.h"
#include <iostream>
#include <iomanip>

using namespace std;

int* generateNumbers(int n, int m) {

    // Intialize random number
    srand(static_cast<unsigned int>(time(NULL)));

    // Declare array size to generate random numbers based on what is between 1 to (m)
    int* numbers = new int[n];

    for (int i = 0; i < n; i++) {
        numbers[i] = (rand() % m) +1;
        cout << numbers[i]<< "  " << endl;

    }

    return numbers;


}

void Game::guessingGame(int n, int m) {
    int* p;
    int sum = 0;

    // Call the generateNumber function
    generateNumbers(n, m);
    
    // Declare array based on user guesses
    inputGuess = new int[n];

    p = generateNumbers(n,m);

    for (int i = 0; i < n; i++) {
        cin >> inputGuess[i];
    }
    // See if the user guesses and computers answers match up
    for (int i = 0; i < n; i++) {
        for (int j = 0; i < n; j++) {
            if (p[i] == inputGuess[j]){  //Where I keep getting the C6385 Warning
                sum++;
                break;
        }
        }
    }
    
}

The C6385 warning documentation states:

The readable extent of the buffer might be smaller than the index used to read from it. Attempts to read data outside the valid range leads to buffer overrun.

https://docs.microsoft.com/en-us/cpp/code-quality/c6385?view=msvc-160

Your second if statement compares i < n instead of j < n and since i is never modified inside it will run forever. This causes the warning since you'll access memory out of bounds. Fix the comparison.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM