导致以下程序中出现运行时错误的原因

What causes run time error in the following program?

本文关键字:运行时错误 程序      更新时间:2023-10-16

我正在使用这个简单的函数来创建一个新的节点

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;

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

char *word更改为char word[100];

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字符串。

您的错误是由于word没有分配内存。

您可以像其他答案中那样使用遗留的C功能来解决这个问题,也可以实际编写idomatic C++。

createNewNode函数中完成的所有初始化都应该在node构造函数中完成。您应该使用std::string而不是char*,以避免出现当前的内存分配故障。您还应该保护node类的成员,而不是提供赋值函数来将它们从树中附加/分离,这样您就不需要手动执行。

您的程序在以下行中崩溃,

strcpy(n->word,word);

因为,struct node 中的n->word

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;
}

strcpy(n->word, word)将输入字符串复制到尚未初始化的n->word中。为了使该解压缩正常工作,n->word必须指向已分配的缓冲区。

strdup函数为您分配该缓冲区,并将输入字符串复制到该缓冲区中,例如:

n->word = strdup(word);