Warning C6385 Reading invalid data from 'result'. 21
Warning C6386 Buffer overrun while writing to 'result'. 12
Warning C6385 Reading invalid data from 'number'. 58
When raised to a power higher than 3 biological errors.
#include <iostream>
#include <string>
using namespace std;
Column multiplication function. First and second warning is here.
void MultiplyArrays(int* ar1, int* len1, int* ar2, int len2) {
int resultLen = *len1 + len2;
int* result = new int[resultLen]();
for (int i = *len1-1; i > -1; --i) {
int carry = 0;
for (int j = len2-1; j > -1; --j) {
int tempSum = result[i + j + 1] + ar1[i] * ar2[i] + carry;
result[i + j + 1] = tempSum % 10;
carry = tempSum / 10;
}
result[i] += carry;
}
int i = 0;
while (i<resultLen && result[i]==0)
++i;
for (int j = 0; j < i; j++) {
result[j] = result[j + i];
--resultLen;
}
*len1 = resultLen;
for (int i = 0; i < resultLen; i++) {
ar1[i] = result[i];
}
delete[] result;
}
Recursive exponentiation function.
void RaisePowerTwo(int* len, int* array, int power) {
if (power == 1)
array[0] = 2;
else if (power % 2 == 1) {
RaisePowerTwo(len, array, power - 1);
int* timeAr = new int[1];
timeAr[0] = 2;
MultiplyArrays(array, len, timeAr, 1);
delete[] timeAr;
}
else if (power % 2 == 0) {
RaisePowerTwo(len, array, power / 2);
MultiplyArrays(array, len, array, *len);
}
}
Main function. Third warning is here
int main() {
int n;
cin >> n;
int length = 1;
int* number = new int[length]();
RaisePowerTwo(&length, number, n);
for (int i = 0; i < length; ++i)
cout << number[i];
delete[] number;
return 0;
}
Please help, I've been struggling with this problem for two weeks now. Only today I thought of asking a question on Stask Overflow, this is my first question.
There are a few other bugs, but the main issue is that you copy a longer array into a shorter array, and thereby write data outside the range of the shorter array. It happens in this piece of code in
MultiplyArrays:Here
ar1has "only" a size of*len1(before it is overwritten byresultLen), while you are writing toar1[resultLen-1]which can be an out-of-range index forar1. Realise that thisar1is thenumberarray that you defined inmainand can only hold one integer. You need to allocate memory for the growing array.In C++ you should use
vectorfor this purpose.Some of the other issues are:
ar2[i]is wrong. The right index to use isj.for (int j = 0; j < i; j++) {is a wrong. It doesn't take into account how many values there are in the result array.using namespace stdHere is a correction, using
vector: