我在类中使用 malloc 或 new 来获取变量,然后我得到一个 SIGABRT,我在其他 cpp 文件中测试 malloc 和 new,它运行良好。你能告诉我原因:P 错误发生在两行:(在函数 Trie::Insert(char*))
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( ){}
特里.cpp