简体   繁体   中英

Buffer overrun warning

This script spreads all the digits of a number in an array, so that by doing this: spread(number)[position] you can access the digit with relative position. Now the compilers gives me a Buffer overrun warning (C6386), which I assume is caused by exceeding an array bounds (correct me if I'm wrong), but I scripted the function such that such thing doesn't happen, and the program is still malfunctioning

#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 . . .
*/

The body of your for loop interferes with your end condition:

  • P=0, num=377, size(num) = 3, P <= 2 = true
  • P=1, num=37, size(num) = 2, P <= 1 = true
  • P=2, num=3, size(num) = 1, P <= 0 = false

The fix is to calculate size(num) up front and use that in your loop condition:

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;
}

You will store the digit until the number is 0. Use this condition and your Code works. But you have memory leaks... You have to free dynamic memory!

Update: There is a short code, which works ;-)

#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;
}

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