多个对象的插入时出现分段错误

Segmentation fault on instationation of more than 1 object

本文关键字:分段 错误 插入 对象      更新时间:2023-10-16

我有一个名为"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;

namestr都是字符*类型。您正在取消引用这些指针。这意味着您查看它们指向的内存位置并将其解释为 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
};

看看这如何更简单?现在,您不必弄乱指针,这些指针使用起来很痛苦。所以,简而言之:使用标准库。并得到一本好书。真。