2012-11-21 24 views
0

我在類中使用malloc或new來獲取變量,然後我得到一個SIGABRT,我測試malloc和新的在其他cpp文件中,它效果很好。你能告訴我原因:在兩條線發生P 錯誤:(函數特里::插入(字符*))我使用malloc或類中的新變量,然後我得到一個SIGABRT

int* pN = new int; 

PNODE node = (PNODE)malloc(sizeof(struct NODE)); 

別人是正確的

所有代碼:

#define CHARSIZE 26 
#include<assert.h> 
#include<stdlib.h> 
#include<iostream> 
using namespace std; 
typedef struct NODE { 
    char key; 
    struct NODE* child[ CHARSIZE ]; 
}* PNODE,*TRIE; 

class Trie{ 
public: 
    Trie(); 
    void Insert(char* sData); 
    void Show(); 
    void ShowTrie(PNODE root); 
    void Delete(struct NODE* pNode); 
    struct NODE* Search(char* sData); 
    void DeleteTrie(); 
    ~Trie(); 
private: 
    PNODE pRoot; 
    static char colls[]; 
}; 
char Trie::colls[] = "abcdefghijklmnopqrstuvwxyz "; 
Trie::Trie(){ 
    //root create 
    this->pRoot = NULL; 
    this->pRoot = (PNODE)malloc(sizeof(struct NODE)); 
    this->pRoot->key = ' '; 
    for(int i=0; i<CHARSIZE+1; i++){ 
     this->pRoot->child[ i ] = NULL; 
    } 
} 
void Trie::Insert(char* sData){ 
    //stick 
    if(sData==NULL || *sData == '\0'){ 
     return; 
    } 
    PNODE p = this->pRoot; 

    char* pData = sData; 
    //same error sigabrt ginal 
    int* pN = new int; 
    //still error 
    //PNODE node = (PNODE)malloc(sizeof(struct NODE)); 
    while(*pData!='\0'){ 
     //如果對應位置的指針爲空 
     if(p->child[ *pData-'a' ]==NULL){ 
      //make new Node 
      PNODE node = (PNODE)malloc(sizeof(struct NODE)); 

      node->key = *pData; 
      int i = 0; 
      while(i < CHARSIZE){ 
       node->child[i] = NULL; 
       i++; 
      } 
      p->child[*pData-'a'] = node; 
     } 

     p = p->child[ *pData-'a' ]; 
     pData++; 
    } 
} 
void Trie::Show(){ 
    ShowTrie(this->pRoot); 
} 
void Trie::ShowTrie(PNODE root){ 
    if(root==NULL){ 
     return; 
    }else{ 
     cout<<root<<endl; 
     //cout<<root->key<<" "; 
     for(int i=0; i<CHARSIZE; i++){ 
      ShowTrie(root->child[i]); 
     } 
    } 
} 
void Trie::Delete(struct NODE* pNode){ 

} 
struct NODE* Search(char* sData){ 


    return NULL; 

} 
Trie::~Trie(){} 

trie.cpp

+1

您正在使用C++,使用'new'和'delete'運算符。 – Aesthete

+0

就我而言,值得推廣到C++用法的* only * C內存分配函數是'realloc()',甚至只在非常有限的情況下。作爲一個通常很少被破壞的規則,除非你知道你在做什麼,否則在C++中使用** new **,** delete **和** delete [] **,如果你是'malloc (),你不知道。 – WhozCraig

+0

「p-> child [* pData-'a']」看起來有點冒險,你確定你總是得到一個0 ..索引值嗎?可能更好地使用std :: map –

回答

3

由於堆棧/堆已損壞而出現此錯誤。在構造函數中,有一個在for循環的錯誤:

`特里::特里(){ ...

for(int i=0; i<CHARSIZE+1; i++){ ***// should not +1, just i < CHARSIZE*** 

    this->pRoot->child[ i ] = NULL; 

}` 

當堆被損壞,在調試版本,將發生在一個異常下一次內存分配,因爲堆驗證。

+0

我想表決答案,但我現在只有9'。所以。謝謝你,P和對不起 – user1755394

+0

沒關係。 :) – Matt

相關問題