代码导致数据结构操作崩溃
Code crashes data structure manipulation
在下面的代码中,对于每个节点都包含一个指向所有子节点(类型为节点)的指针的指针
在崩溃的行中,我正在为child_array分配内存,并返回一个类型为 node * 的指针。
现在在我的实际节点中,我将 ptr 到 ptr child_array的值设置为
有人可以解释为什么这会崩溃。在数学上,方程的两边都是(节点*)。
我可以猜到的一件事是,当我取消引用child_array一次以分配节点*时,取消围栏的值可能指向垃圾,而没有初始化。在这种情况下,我如何以及何时安全地初始化它?
#include "stdafx.h"
#include <iostream>
using namespace std;
struct node
{
int val;
int num_child;
node** child_array;
};
node *head = NULL;
node* addelement(int parent_id)
{
cout << " You are the child of " << parent_id << endl;
int val, child_count;
cout << "Enter value of element" << endl;
cin >> val;
cout << "Enter no of children" << endl;
cin >> child_count;
node* new_node = new node;
if(new_node)
{
new_node->num_child = child_count;
new_node->val = val;
node *child_head = (node *)new node[child_count];
下面捣碎的 lINE
*(new_node->child_array) = child_head;
}
else
{
//assert(false);
}
for( int i=0; i<child_count; i++)
{
new_node->child_array[i] = addelement(val);
}
return new_node;
}
void printTree(node *head)
{
if(head!=NULL)
{
cout << head->val << endl;
for( int i=0; i<head->num_child;i++)
{
printTree(head->child_array[i]);
}
}
}
int _tmain(int argc, _TCHAR* argv[])
{
head = addelement(0);
printTree(head);
cout << endl;
cout << " Tree Elementsn";
printTree(head);
return 0;
}
取消引用未初始化的指针并写入未分配的内存:
*(new_node->child_array) = ...
还有一个概念问题。您是要创建node
数组还是node*
数组?
相关文章:
- 当回溯以零开始时,如何调试崩溃
- 为什么在popback()操作之后,它仍然打印完整的矢量
- 重载操作程序时出错>>用于类中的字符串 memebr
- 内联映射初始化的动态atexit析构函数崩溃
- 执行函数时导致崩溃的变量
- 程序崩溃并显示"std::out_of_range"错误
- 对字符串进行位操作
- CoInitialize()在单独的线程上崩溃而不返回
- 使用调试/崩溃报告将应用程序部署到客户端
- 我可以在 C++ 中的函数体之外进行操作吗?
- 排序时无法执行交换操作.我做的时候它会崩溃.为什么
- 对 NULL 值的按位操作是否会使C++中的代码崩溃
- 代码导致数据结构操作崩溃
- 本机C++程序在使用 C++/CLI 和 C# 互操作 DLL 启动时崩溃
- Qt Creator在使用其C++编辑器操作文件时崩溃
- 在简单的数学操作崩溃到桌面
- Boost TCP服务器在执行asio::write操作时客户端断开,导致服务器崩溃
- RenderTexture在访问操作(Cocos2d-x)时崩溃
- 我的c++和c#互操作在64位崩溃了,为什么?指针的大小
- 每次我将第一个整数放入数组时,方法都会崩溃.操作不良