导致以下程序中出现运行时错误的原因
What causes run time error in the following program?
我正在使用这个简单的函数来创建一个新的节点
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);
相关文章:
- 为什么程序在 c++ 中迭代 emtpy 向量时会抛出运行时错误
- 调用 java 的回调() 时应用程序崩溃.由于 detatchThread 而获得运行时错误
- QT C++防止关闭应用程序时出现运行时错误
- 运行 libpng 应用程序时出现运行时错误
- 向 Kattis 在线评委提交 c++ 程序时出现未知运行时错误
- Qt 应用程序中与Qt版本相关的运行时错误
- 在计算机级别,应用程序以二进制方式运行,然后当发生运行时错误时,它如何呈现回错误代码
- 排列程序无法写入数组 - 运行时错误
- 为什么我的程序在删除以下代码中的注释后会出现运行时错误?
- c++分段错误:为什么这个程序给出运行时错误(SIGSEGV)
- 使用MinGW gcc/g++(nuwen发行版)编译的程序出现运行时错误
- QT程序无法编译/具有运行时错误(IDE:CodeBlocks/QTCreator)
- 程序C++运行时错误
- 基于graphics.h的程序出现代码块运行时错误
- OCCI C++应用程序的Visual Studio调试运行时错误
- 在运行时从应用程序获取PE标头时发生运行时错误
- 运行时错误,当我运行程序,但当我使用调试器时没有
- C 程序对我有用,但在线显示运行时错误
- 运行时错误:程序已停止响应
- 运行时错误C++程序:检测到glibc,munmap_chunk(),指针无效