缓冲区溢出警告



此脚本将数组中数字的所有数字展开,因此通过执行以下操作:spread(number)[position],您可以访问具有相对位置的数字。现在编译器会给我一个Buffer overrun警告(C6386(,我认为这是由超出数组界限引起的(如果我错了,请纠正我(,但我编写了函数的脚本,这样就不会发生这种事情,并且程序仍然在中出现故障

#include <iostream>
#include <math.h>
using namespace std;
unsigned int size(long long int num)
{
unsigned int size = 1;
while (num >= pow(10, size)) size++;
return size;
}
int* spread(int num)
{
unsigned int digit;
int* nums = new int[size(num)];
for (unsigned int P = 0; P <= size(num) - 1; P++)
{
digit = num - num / 10 * 10;
num /= 10;
nums[P] = digit; //Right in this line the program doesn't seem to behave correctly
}
return nums;
}
int main()
{
cout << split(377)[0] << endl;
cout << split(377)[1] << endl;
cout << split(377)[2] << endl;
system("PAUSE");
return 0x0;
}
/*
Output of the program:
7
7
-842150451 <-- there should be a 3 here
Press any key to continue . . .
*/

for循环的主体会干扰您的最终条件:

  • P=0,num=377,size(num(=3,P<=2=真
  • P=1,num=37,大小(num(=2,P<=1=真
  • P=2,num=3,大小(num(=1,P<=0=错误

修复方法是提前计算size(num),并将其用于循环条件:

int numdigits = size(num);
for (int P=0; P < numdigits; P++) { ... }
{
unsigned int digit;
int* nums = new int[size(num)];
int P = 0;
while(num!=0)
{
digit = num - num / 10 * 10;
num /= 10;
nums[P++] = digit; //Right in this line the program doesn't seem to behave correctly
}
return nums;
}

您将存储该数字,直到数字为0。使用此条件,您的代码就会工作。但是你有内存泄漏。。。你必须释放动态内存!

更新:有一个短代码,有效;-(

#include <iostream>
#include <vector>
#include <string>
using namespace std;
vector<size_t> spread(int const num)
{
string number = to_string(num);
vector<size_t> digits;
for(size_t i = 0; i < number.size(); ++i)
{
digits.push_back(number[i] - '0');
}
return digits;
}
int main()
{
auto vec = spread(12345000);
for (auto elem : vec)
{
cout << elem << endl;
}
system("PAUSE");
return 0x0;
}

最新更新