digits[a] = 1;
digits[1] = a;
//Note: Both of these were just debugging stuff to figure out why it was crashing.
Here is the code.
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
#include <string>
using std::string;
//Begins the definition of the radix class.
class radix
{
public:
radix(char _digits[], int _base)
{
reassign_radix(_digits, _base);
}
string radix::get_value()
{
return radix_value;
}
int radix::reassign_radix(char _digits[], int _base)
{
if(_base) base = _base;
else return 0;
if(_digits == NULL) return 0;
if(digits != NULL) delete [] digits;
if(digits == NULL) digits = new char[base];
//It crashes on this loop.
for(int a = 0; a < base; a ++)
digits[a] = _digits[a];
return 1;
}
void radix::assign(int value = 0)
{
decimal_value = value;
string storage;
int length = 0;
int digit = 0;
do
{
digit = value % base;
value = value / base;
storage += digits[digit];
length ++;
} while(value != 0);
radix_value = new char[length];
for(int n = length - 1; n >= 0; n --)
radix_value += storage[n];
}
private:
string radix_value;
int decimal_value,
base;
char* digits;
};
int main()
{
const int base = 8;
char digits[base] = {'0', '1', '2', '3', '4', '5', '6', '7'}; //, '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
radix blarg(digits, base);
//blarg.assign(8);
//cout << blarg.get_value() << endl;
//int a;
//cin >> a;
return 0;
}
Your problem is this: You delete the allocated memory, but you never reallocate it, and then you try to access the unallocated memory. Oops! Where might we have gone wrong?
Now, when digits is not null; that is, it points to a memory location, you delete the memory array at that location. Keep in mind now that when you delete memory, it doesn't automatically set the pointer to NULL. So the second if() statement here fails, and the memory is never reallocated. The two ways you might solve this are to either set digits to NULL in the first if(), or remove the second if() and put the digits = new... statement within the first if().
Hiead