![](/img/trans.png)
[英]Why does this code emit buffer overrun warnings(C6385/C6386) in code analysis on Visual Studio 2012?
[英]How do I fix compiler warnings C6386 and C6385?
對於我正在編寫的程序,我需要創建一個具有用戶定義大小的數組,以及 -15 和 15 之間的隨機值。因此,我將 srand 與動態數組轉換一起使用。 這是我下面的完整代碼:
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
//initialize variables
double minValue;
double maxValue;
double firstQuartile;
double thirdQuartile;
double skewness;
int size;
std::cout << "Please enter the size of the data set: "; //get data set size from user
std::cin >> size;
int* dataSet = new int[size];
cout << endl << "These are the randomly generated values: ";
srand(static_cast<unsigned int>(time(NULL)));
int i = size;
for (int x = 0; x < i; x++) //generate random numbers
{
dataSet[i] = (rand() % 31) - 15;
cout << dataSet[i] << " ";
}
}
雖然它仍然可以編譯,但我需要它在沒有錯誤的情況下這樣做,而我在下面突出顯示的部分導致了兩個我不知道如何修復的錯誤。
int i = size;
for (int x = 0; x < i; x++) //generate random numbers
{
dataSet[i] = (rand() % 31) - 15;
cout << dataSet[i] << " ";
}
C6386寫入“dataSet”時緩沖區溢出:可寫大小為“size*4”字節,但可能會寫入“i”字節。
和
C6385從'dataSet'讀取無效數據:可讀大小為'size*4'字節,但可以讀取'i'字節。
在這個循環中索引變量 x 而不是 i。
所以像這樣改變循環
int i = size;
for (int x = 0; x < i; x++) //generate random numbers
{
dataSet[x] = (rand() % 31) - 15;
cout << dataSet[x] << " ";
}
事實上,變量 i 是多余的,使代碼容易出錯。 為什么不寫
for (int i = 0; i < size; i++) //generate random numbers
{
dataSet[i] = (rand() % 31) - 15;
cout << dataSet[i] << " ";
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.