我试图通过静态HUFFMAN算法编写程序来压缩/提取文件。我已经完成了我的代码,当我用文件.txt测试时,一切都还可以。但是当我用另一个文件(例如:mp3,docx等)测试时,编译器会警告错误:"无效的空指针" 。 detail picture
过了一会儿,我找到了导致错误的行,但我无法理解为什么这行错误:" .exe触发了断点。" detail picture
这是我的结构和功能:
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);
}
}
答案 0 :(得分:0)
第一部分包含致命错误(我怀疑它是否编译):
struct BITCODE
{
char *bit;
int size;
}
BITCode **bitTable;
您正在混淆大小写和结构定义。你需要一个分号来表示结构的结束:
int size;
}; // a semicolon
BITCODE bitTable; // CAPITALIZATION!
然后,你没有为bitTable
分配任何内存。预计你应该这样做。
// somewhere in the beginning:
bitTable = new BITCODE*[MAX];
// inside createBit_Table()
bitTable[num] = new BITCODE[MAX_UNSIGNED_CHAR];