多个对象的插入时出现分段错误
Segmentation fault on instationation of more than 1 object
我有一个名为"Vertex.hpp"的类,如下所示:
#include <iostream>
#include "Edge.hpp"
#include <vector>
using namespace std;
/** A class, instances of which are nodes in an HCTree.
*/
class Vertex {
public:
Vertex(char * str){
*name=*str;
}
vector<Vertex*> adjecency_list;
vector<Edge*> edge_weights;
char *name;
};
#endif
当我实例化 Vector 类型的对象时,如下所示:
Vertex *first_read;
Vertex *second_read;
in.getline(input,256);
str=strtok(input," ");
first_read->name=str;
str=strtok(NULL, " ");
second_read->name=str;
当实例化 1 个以上 Vector 类型的对象时,会发生分段错误。如果实例化了 1 个以上的对象,为什么会发生这种情况,如何允许实例化多个对象?
*name=*str;
在首先使指针指向某物之前,无法取消引用指针。
你的意思可能是这样的:
Vertex(char * str) {
name=strdup(str);
}
但是你真的应该使用std::string
.
我认为复制字符串的方式是错误的。
*name=*str;
name
和str
都是字符*类型。您正在取消引用这些指针。这意味着您查看它们指向的内存位置并将其解释为 char。
当您第一次调用它时,某些东西位于str
指向的位置,并且它的第一个字符被复制到随机地址(因为您从未初始化过name
)。
第二次你就没那么幸运了。 strtok
在cplusplus上呼吁NULL 返回NULL strtok
现在您尝试使用由空指针指向的内存,这很糟糕。
您需要为name
分配内存并使用适当的复制功能。
name = new char[SomeMaxLenght];
strcpy(name, str);
这是一种
非常C的做事方式,在现代C++中非常不推荐。请记住,C++应该被视为不同的语言,而不是 C 的严格超集。
首先,你应该通过查看该列表来获得一本好书,因为您似乎缺少许多基础知识。
至于你的问题,主要问题是name
是未初始化的,所以你遇到了所谓的未定义行为(即任何事情都可能发生;在你的情况下,它在第二次实例化时崩溃)。我可以深入了解如何通过动态分配内存来修复它,但为什么要打扰呢?只需使用std::string
:
class Vertex {
std::string name; // string instead of char *
public:
Vertex(const std::string &str) { // pass by const reference
name = str; // I should really use an initializer list there, but oh well
}
// the rest of the class is the same
};
看看这如何更简单?现在,您不必弄乱指针,这些指针使用起来很痛苦。所以,简而言之:使用标准库。并得到一本好书。真。
相关文章:
- 在某些循环内使用vector.push_back时出现分段错误
- 为什么在运行时没有向我们提供有关分段错误的更多信息?
- 如何解决gcc编译器优化导致的centos双编译器设置中的分段错误
- 当我的阵列太大时出现分段错误
- 分段错误当我试图运行程序时出错
- 在c++中初始化矩阵时出现分段错误(核心转储)
- 尝试使用集合函数时出现分段错误
- 我无法缩小此分段错误的原因
- g++的分段错误(在NaN上使用to_string两次时)
- 我是如何在这段代码中出现分段错误的
- 创建结构的数组时遇到分段错误
- 在c++中键入向量中的所有值后,得到分段错误(核心转储)
- 在 c++ 中实现 Trie 时出现分段错误
- 为什么 fstream 在打开带有格式的文件时会导致分段错误?
- 为什么我遇到分段错误?
- 动态类的分段错误(家庭作业问题)
- 分段错误 - 读取初始化指针的数组
- 如何摆脱C ++中的分段错误错误?
- 使用 CTYPE 时出现分段错误
- 为什么代码给出分段错误?