【发布时间】:2020-08-05 21:52:32
【问题描述】:
各位,我需要一些帮助。我在写入“AnArray”时收到警告 C6386 缓冲区溢出:可写大小为“nrows*8”字节,但可能会写入“16”字节。在以下代码上
#include <math.h>
void SubMain(int, int);
int CSTEBit(int, int, int);
double Fact(int);
double Perm(int, int);
int Comb(int, int);
int main()
{
SubMain(13, 5);
}
void SubMain(int N, int R)
{
int** AnArray;
int nrows = Comb(N, R) + 1;
int ncolumns = 8;
int Pos;
int Count;
AnArray = new int* [nrows];
for (int i = 0; i < nrows; i++)
AnArray[i] = new int[ncolumns];
for (int a = 0; a < nrows; a++)
{
for (int b = 0; b <= 7; b++)
AnArray[a][b] = 0;
}
Pos = 0;
Count = 0;
do
{
Pos += 1;
if ((CSTEBit(3, AnArray[Pos][7], 4) == 0) && (CSTEBit(3, AnArray[Pos][7], 5) == 0))
Count += 1;
} while (Count != nrows - 1);
AnArray[Pos][7] = CSTEBit(1, AnArray[Pos][7], 4);
}
int CSTEBit(int CSTE, int Byt, int Bit)
{
int tempCSTEBit = 0;
if (Bit < 8)
{
int Mask = (int)pow(2, Bit);
switch (CSTE)
{
case 0:
tempCSTEBit = (int)(Byt && ~Mask);
break;
case 1:
tempCSTEBit = (int)(Byt | Mask);
break;
case 2:
tempCSTEBit = (int)(Byt ^ Mask);
break;
case 3:
if ((Byt & Mask) > 0)
{
tempCSTEBit = 1;
}
else
{
tempCSTEBit = 0;
}
break;
default:
tempCSTEBit = Byt;
break;
}
}
else
{
tempCSTEBit = Byt;
}
return tempCSTEBit;
}
double Fact(int N)
{
double tempFact = 0;
if (N <= 1)
{
tempFact = 1;
}
else
{
tempFact = N * Fact(N - 1);
}
return tempFact;
}
double Perm(int N, int R)
{
double tempPerm = 0;
int a = 0;
double b;
b = 1;
if (N < R)
{
tempPerm = 0;
}
else
{
for (a = (N - (R - 1)); a <= N; a++)
{
b = b * a;
}
tempPerm = b;
}
return tempPerm;
}
int Comb(int N, int R)
{
int tempComb = 0;
if (N < R)
{
tempComb = 0;
}
else
{
tempComb = (int)(Perm(N, R) / Fact(R));
}
return tempComb;
}
变量 Pos 永远不会高于用于初始化 AnArray 的 Comb 函数返回的值。提前感谢您的任何回答。
【问题讨论】:
-
我建议你拿起一本关于现代 C++ 的好书,从头到尾阅读,然后开始使用容器和智能指针(如果在采用容器后需要的话),然后停止尝试像这样手动管理内存是 C++98(或更早版本)。老实说,这看起来像是用 C++ 编译器编译的糟糕的 C。
-
请创建一个minimal reproducible example。没有一个意味着每个试图提供帮助的人都必须先编译代码,然后才能尝试重现诊断。在这种情况下,甚至不清楚是否可以在不主要猜测缺失部分的情况下回答问题,这对任何人都没有帮助。
-
克里斯,你是绝对正确的。我很抱歉,但这是我的第一篇文章。我编辑了代码,现在您可以重现警告
-
这只是一个警告。这个警告表明指定缓冲区的可写范围可能小于用于写入它的索引。这可能会导致缓冲区溢出。在我看来,这可能是代码分析误报。我建议您可以将问题发布到Developer Community 以获得更好的帮助。
标签: c++ visual-studio warnings