我在類中使用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
您正在使用C++,使用'new'和'delete'運算符。 – Aesthete
就我而言,值得推廣到C++用法的* only * C內存分配函數是'realloc()',甚至只在非常有限的情況下。作爲一個通常很少被破壞的規則,除非你知道你在做什麼,否則在C++中使用** new **,** delete **和** delete [] **,如果你是'malloc (),你不知道。 – WhozCraig
「p-> child [* pData-'a']」看起來有點冒險,你確定你總是得到一個0 ..索引值嗎?可能更好地使用std :: map –