簡體   English   中英

無法為結構分配內存

[英]Cannot allocate memory for a structure

我正在嘗試編寫一個程序來通過靜態HUFFMAN算法壓縮/提取文件。 我已經完成了代碼,當我使用文件.txt進行測試時,一切正常。 但是,當我測試另一個文件(例如:mp3,docx等)時,編譯器會警告錯誤: “無效的空指針” 詳細圖片

片刻之后,我找出了導致錯誤的行,但是我不明白為什么該行是錯誤的: “。exe觸發了斷點。” 詳細圖片

這是我的結構和功能:

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);
}
}

第一部分包含一個致命錯誤(我懷疑它會編譯):

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];

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM