#include<iostream>
#include<set>
#include<stdlib.h>
using namespace std;
typedef set<short> pos;
typedef struct tree
{
pos first;
}tree;
class check
{
public:
pos last;
void check_set();
};
void check::check_set()
{
tree *root,p;
root=(tree*)malloc(sizeof(tree));
root->first.insert(2);//SEGMENTATION FAULT HERE WHY???
p.first.insert(3);//NO SEGMENTATION FAULT
}
int main()
{
check obj;
obj.check_set();
obj.last.insert(1);//NO ERROR HERE
return 0;
}
1
A
回答
4
使用new
,而不是malloc
分割故障。
malloc
只分配内存,它不会以任何方式对它进行初始化,也不会构造将存在于该内存中的对象。另一方面有new
构造了C++对象。因此,要获得一个有效的tree
对象(用正确初始化first
成员),使用此:
root = new tree();
以后,当你想释放对象,使用delete
:
delete root;
1
的问题是, root
不指向tree
,它指向一个大小为tree
的已分配内存块。然后尝试在内部成员上执行set
操作时,该集合(具有其内部结构和精心修饰的指针)实际上不在那里。
1
malloc
不调用构造函数,所以也不tree
的构造也不std::set
的构造曾经被调用和你想填充未构造std::set
。这就是为什么你会遇到段错误。
使用new
为:
root=(tree*)malloc(sizeof(tree)); //only allocates memory
root = new (root) tree; //constructs the object in the memory pointed to by root.
//deallocation
root->~tree(); //call the destructor
free(root); //and then deallocate the memory
2
tree *root,p; root=(tree*)malloc(sizeof(tree)); root->first.insert(2);//SEGMENTATION FAULT HERE WHY??? p.first.insert(3);//NO SEGMENTATION FAULT
p被分配在堆栈上:作为
root = new tree(); //this allocates memory, and constructs the object as well.
//deallocation
delete root; //call the destructor, and then deallocate the memory
还是使用投放新!所以它的构造函数被调用。另一方面,根的构造函数是永远不会调用!你只是分配一个树需要的大小的内存!
相关问题
- 1. 的jQuery得到一棵树
- 2. 这棵树布局为什么给我一个无限循环?
- 3. 当我试图插入数据到表中,得到错误
- 4. 试图走一棵树,总是得不到结果
- 5. 为什么我得到404错误试图休息一下?
- 6. 为什么我不能在我的地图中插入/插入?
- 7. 试图插入一个地图,我得到
- 8. 为什么我得到一个错误,当我尝试git的承诺--amend
- 9. 得到一棵树结构的孩子
- 10. 为什么我的单元测试试图插入一个记录,当我不问它?
- 11. 为什么我没有得到20151231当输入为2.0151231E7F
- 12. 二叉搜索树 - 复制一棵树到另一棵树
- 13. 为什么当我尝试插入和1 = 1之前限制0,1我得到SQL错误?
- 14. 我想找到一棵树是否是另一棵树的子树,并运行到ArrayList比较prolem
- 15. 我得到一个PHP错误,我无法得到为什么我得到它
- 16. 当我尝试插入其中BLOB数据类型当我试图执行INSERT语句,我得到了下面的错误,我得到一个错误
- 17. 为什么我得到重复的行插入?
- 18. 我得到Metadata.framework错误,当我尝试导入图像
- 19. 为什么我得到空数组,当我看到数据
- 20. TortoiseSVN给我一棵树冲突
- 21. 我该如何创建一棵树?
- 22. 为什么我得到空
- 23. 为什么我得到.UnauthorizedAccessException?
- 24. 为什么我得到IllegalFormatConversionException?
- 25. 为什么我得到System.IndexOutOfRangeException:EmpPassword
- 26. 为什么我得到linebreaks?
- 27. 为什么我得到flask.redirect
- 28. 为什么我得到零
- 29. 为什么我得到java.lang.ClassNotFoundException?
- 30. 为什么我得到System.Data.DataRow?