【问题标题】:Why do my pointers cause a segfault?为什么我的指针会导致段错误?
【发布时间】:2017-11-12 03:26:37
【问题描述】:
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <vector>
using namespace std;
  struct student
  {
    char name[50];
    char lname[50];
    int id;
    float GPA;
  };
void toAdd(vector<student*> *plist);
void toDelete(vector<student*>* plist);
void toPrint(vector<student*>* plist);
int main(){
  vector<student*> list;
  vector<student*>* plist = &list;
  char input[80];
  bool running = true;
  while (running == true){
    cout << "What would you like to do?" << endl;
    cin.getline (input,80);
    if(strcmp (input, "ADD") == 0){
      toAdd(plist);
    }
    else if(strcmp (input, "DELETE") == 0){
    }
    else if(strcmp (input, "PRINT") == 0){
    }
    else{
      cout << "That is not a valid response!" << endl;
        }
  }
}

void toAdd(vector<student*> *plist){
  student* stu;
  cout << "What a test!" << endl;
  cout << "First Name: ";
  cin.getline(stu->name,20);
  cout << "Last Name: ";
  cin.getline(stu->lname,20);
  cout << "ID: ";
  cin.getline(stu->id);
  cout << "GPA: ";
  cin.getline(stu->GPA);
  plist->push_back(stu);
}
void toDelete(){

}
void toPrint(){
}

我不明白我做错了什么。我一直在研究这段代码几个小时,真的需要一些帮助。当我运行代码并尝试输入名称时,我收到错误“分段错误(核心转储)”。我觉得这可能真的很简单,但是网上的解释都没有帮助我。 :(

【问题讨论】:

  • 你不需要那么多星星。首选字符串而不是字符数组。
  • 你为什么使用指针?
  • toAdd 取消引用未初始化的指针 stu,因此您的程序表现出未定义的行为。
  • 因为他们没有指向任何东西?
  • 一:不用plist,了解references。二:没有必要将 pointers 存储到向量中的结构中。三:了解std::string。四:了解std::getline。五:要么开始在课堂上更加专注,要么get better beginners books

标签: c++ pointers vector segmentation-fault


【解决方案1】:

您取消引用未初始化的指针。打电话之前

cin.getline(stu->name,20);

你需要先使用new分配它的内存

student* stu = new student;

【讨论】:

  • 糟糕的建议。
  • 这种方法会在短时间内造成内存泄漏。该方法应该只返回一个student
  • 那么 OP 需要确保在使用 plist 完成后正确释放其内存
  • 至少使用std::unique_ptr&lt;student&gt; 但实际上不需要指针。
  • @AluanHaddad 问题不在于是否需要指针。问题是为什么指针不起作用。即使有其他可用的工具,人们仍然需要学习如何使用指针。
【解决方案2】:

当您试图访问不允许的内存位置区域(读取或写入)时,通常会导致 Seg 错误。在下面的行中,在 toAdd() 方法中:

cin.getline(stu->name,20);

stu->name 相当于: (*stu).name 试图取消引用未初始化的指针。

此外,建议使用智能指针(原始(常规)指针的包装器),因为它允许您更有效地管理为该指针分配的内存。您可以选择唯一或共享智能指针。

【讨论】:

  • 你是对的,但你应该解释为什么程序存在根本性缺陷,可以重写为短小,甚至不使用这种技术。
猜你喜欢
  • 2014-01-10
  • 1970-01-01
  • 2013-10-25
  • 2011-11-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多