I'm working on implementation on big integer and meanwhile i found an error in my code which gives me sleepless nights because I'm not really sure what is happening there.
BigNum::BigNum(const BigNum& big_num) {
size = big_num.size;
sign = big_num.sign;
value = newchar[size+1];
strcpy(value, big_num.value);
}
BigNum::~BigNum() {
delete[] value;
value = 0;
size = 0;
}
BigNum BigNum::operator = (const BigNum& big_num) {
if (*this != big_num) {
delete[] value;
size = big_num.size;
sign = big_num.sign;
value = newchar[size + 1];
strcpy(value, big_num.value);
}
return *this;
}
BigNum BigNum::operator* (const BigNum& big_num) {
BigNum *longer = ((*this).size > big_num.size) ? new BigNum(*this) : new BigNum(big_num);
BigNum *shorter = (*this == *longer) ? new BigNum(big_num) : new BigNum(*this);
BigNum *result = new BigNum();
result->initialize_value(longer->size);
result->carry_multiplication(*longer, *shorter);
result->size = strlen(result->value);
result->set_sign(longer->sign*shorter->sign);
delete longer;
delete shorter;
return *result;
}
void BigNum::initialize_value(int arr_len) {
size = arr_len;
value = newchar[size + 1];
std::fill_n(value, size + 1, '0');
value[size] = '\0';
}
BigNum::BigNum(int num) {
set_sign(num);
num = abs(num);
size = get_int_size(num);
value = newchar[size + 1];
num_to_char_array(num);
}
int my_atoi(char c) { return c - CHAR_TO_INT; };
void BigNum::carry_multiplication(const BigNum& longer, const BigNum& shorter) {
int carry = 0;
int row = 0;
for (int i = shorter.size - 1; i >= 0; i--) {
if (row > 0) {
extend_value();
}
for (int y = longer.size - 1; y >= 0; y--) {
int sum = my_atoi(longer.value[y]) * my_atoi(shorter.value[i]);
if (carry != 0) {
sum += carry;
}
carry = 0;
int temp = value[y] - CHAR_TO_INT + sum;
int val = temp % BASE;
value[y] = val + CHAR_TO_INT;
carry = sum / BASE;
}
row += 1;
}
if (carry != 0) {
extend_value();
value[0] = carry + CHAR_TO_INT;
}
}
The error occurs when I try to use operator =*, sometimes I get "access violation reading location" and sometimes it compiles, but then when i try to quit the program it crashes. I'm sure it's about memory but I'm clueless where the bug can be hiding, I'm not returning anything from the heap nor deleting something which i'm using later and the algorithm works fine. Any help on this would be greatly appreciated! Thank you.
$ valgrind ./a.out
==13109== Memcheck, a memory error detector
==13109== Copyright (C) 2002-2015, and GNU GPL'd, by Julian Seward et al.
==13109== Using Valgrind-3.12.0 and LibVEX; rerun with -h for copyright info
==13109== Command: ./a.out
==13109==
==13109== Invalid write of size 1
==13109== at 0x4C2DCA7: strcpy (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==13109== by 0x401D72: BigNum::equals_operation(BigNum const&) (BigNum.cpp:226)
==13109== by 0x401EDC: BigNum::operator+=(BigNum const&) (BigNum.cpp:245)
==13109== by 0x402C9A: main (main.cpp:24)