简体   繁体   English

尝试将cin转换为字符串时出现分段错误?

[英]segmentation fault when trying to cin into a string?

Hi need help with this segmentation fault don't know why i get it 您好,需要有关此细分错误的帮助,不知道我为什么得到它

Movie *newMovie = (Movie*) malloc(sizeof(Movie));
cout << "\nEnter the next movie title:   ";
cin >> newMovie->title;

class Movie {
  public:
    Movie();
    std::string title;
    int year;
    GenreType genre;
};

I checked dgb and segmentation fault comes at the cin line any suggestions? 我检查了dgb并在cin行出现了分段错误,有什么建议吗? btw title is an instance of Movie type and is std::string btw title是Movie类型的实例,并且是std :: string

Don't use malloc in C++ unless you really know you need it (hint: you don't). 除非您真的知道自己需要它,否则不要在C ++中使用malloc (提示:您不需要)。

malloc allocates memory, but it doesn't call any constructors - it just gives you a chunk of bytes to treat as you see fit. malloc分配内存,但不调用任何构造函数-它只是为您提供了一部分字节,您认为合适。 Pretending there's an object in these bytes when none was constructed doesn't work. 假装在没有构造任何字节的情况下在这些字节中有一个对象不起作用。

So just do this: 因此,只需执行以下操作:

Movie *newMovie = new Movie();
cout << "\nEnter the next movie title:   ";
cin >> newMovie->title;

And do you need dynamic allocation in the first place? 您首先需要动态分配吗? Why not just: 为什么不只是:

Movie newMovie;
cout << "\nEnter the next movie title:   ";
cin >> newMovie.title;

The simple amd safe way to do this would be not to use dynamic allocation: 一种简单且安全的方法是不使用动态分配:

Movie newMovie;
cout << "\nEnter the next movie title:   ";
cin >> newMovie.title;
Movie newMovie;
cout << "\nEnter the next movie title ";
cin >> newMovie.title;

will do the trick 会成功的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM