2012-11-21 12 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

相关问题