2015-06-24 85 views
0

我使用这个简单的函数来创建一个新的节点在以下程序中导致运行时错误的原因是什么?

node* Tree::createNewNode(int score, const char* word) 
{ 
    // Create a new node with the information available 
    node* n = new node; 
    n->left=NULL; 
    n->right = NULL; 
    n->parent = NULL; 
    n->score = score; 
    strcpy(n->word,word); 
    return n; 
} 

节点的结构:

struct node 
{ 
    int score; // the score or label of the node 
    char *word; // the word stored in the node 
    node *left; // the pointer to left child of the node 
    node *right; // the pointer to right child of the node 
    node *parent; // the pointer to parent node 
}; 

,我来自另一个函数调用createNewNode功能

temp = t->createNewNode(score,""); 

的函数只能正常运行一次,然后在执行时崩溃:

node* n = new node; 
+3

我建议不要遵循给出的两个答案中的建议,并使用'std :: string'和构造函数而不是传统的C函数。 – TartanLlama

回答

1

您需要为word字段分配内存。您正在尝试将数据复制到word中,但没有为其分配空间。

char *wordchar word[100];

+1

然后他应该使用strncpy(n-> word,word,100 - 1),这样他才不会溢出字缓冲区。 – Matthias

+0

与幻数它是更好的。 – Phong

1
char *word;  // this is a pointer to string, aka this is not a string 
char word[100]; // this is a string 

n->word是初始化。当您使用strcpy时,您正在将word内容复制到未知地址。

未知行为的结果(第一个调用看起来像是工作,第二个调用看起来像是工作,第二个看起来像是程序崩溃)。您需要分配内存空间以在结构中保存word字符串。在下面的行

0

你的程序崩溃,

strcpy(n->word,word); 

,因为n->wordstruct node

char *word; // the word stored in the node 

未分配的任何内存。

使用char array代替char pointer或改变功能的定义是这样的:

node* createNewNode(int score, const char* word, int wordLen) 
{              ^^^^ 
    // Create a new node with the information available 
    node* n = new node; 
    n->left=NULL; 
    n->right = NULL; 
    n->parent = NULL; 
    n->score = score; 
    n->word = (char *) malloc(wordLen); 
    strcpy(n->word,word); 
    return n; 
} 
0

strcpy(n->word, word)复制输入字符串为n->word尚未初始化。为了使这个预期正常工作,n->word必须指向分配的缓冲区。

strdup函数分配该缓冲区为您和拷贝输入字符串到该缓冲区,例如:

n->word = strdup(word); 
1

你的错误是由于word未被分配的内存。

您可以像使用其他答案一样使用旧版C功能来修复此问题,或者您可以真正编写idomatic C++。

createNewNode函数中完成的所有初始化都应该在node构造函数中完成。您应该使用std::string而不是char*来避免您当前拥有的内存分配失败。你还应该保护你的node类的成员,而不是提供增变器来附加/从树中分离它们,所以你不需要手动去做。

相关问题