I'm trying to write a program to compress/extract file by static HUFFMAN algorithm. I've already done my code, when I test with file .txt, everything is okay. But when I test with another file (ex: mp3, docx, etc), the compiler warns the error:"invalid null pointer". detail picture
After a moment later, I find out the line that made the error, but I cannot understand why this line is wrong: ".exe has triggered a breakpoint." detail picture
Here are my structure and function:
struct BITCODE
{
char *bit;
int size;
};
BITCode **bitTable;
#define MAX_UNSIGNED_CHAR 256
#define MAX 10
bool Allocate(int size, bool isCompress)
{
//allocate hufftree
huffTree = new HUFFNode*[size];
if (huffTree == NULL)
return false;
for (int i = 0; i < size; i++)
{
huffTree[i] = new HUFFNode[MAX_NODE];
if (huffTree[i] == NULL)
return false;
}
//allocate frequency and bittable
freq = new long*[size];
if (freq == NULL)
return false;
if (isCompress == true)
{
bitTable = new BITCode*[size];
if (bitTable == NULL)
return false;
}
for (int i = 0; i < size; i++)
{
freq[i] = new long[MAX_UNSIGNED_CHAR];
if (freq[i] == NULL)
return false;
if (isCompress == true)
{
bitTable[i] = new BITCode[MAX_UNSIGNED_CHAR];
if (bitTable[i] == NULL)
return false;
}
for (int j = 0; j < MAX_UNSIGNED_CHAR; j++)
freq[i][j] = 0;
}
}
void createBit_Table(int nRoot, int num)
{
for (int i = 0; i < MAX_UNSIGNED_CHAR; i++)
{
bitTable[num][i].size = 0;
bitTable[num][i].bit = NULL;
}
char bit[MAX];
int size = 0;
processHuffTree(nRoot, bit, 0,num);
}
void processHuffTree(int nNode,char bit[], int size,int num)
{
if (nNode == -1) //If it's a NULL tree
return;
//process node leaf
if (huffTree[num][nNode].left == -1 && huffTree[num][nNode].right == -1)
{
bitTable[num][nNode].bit = new char[size + 1]; //CAUSE ERROR
bitTable[num][nNode].size = size;
for (int i = 0; i < bitTable[num][nNode].size; i++)
bitTable[num][nNode].bit[i] = bit[i];
bitTable[num][nNode].bit[size] = '\0';
}
else
{
//turn left
bit[size] = '0';
processHuffTree(huffTree[num][nNode].left, bit, size + 1,num);
//turn right
bit[size] = '1';
processHuffTree(huffTree[num][nNode].right, bit, size + 1, num);
}
}