【问题标题】:C++ cin.ignore causing a seg fault?C ++ cin.ignore 导致段错误?
【发布时间】:2012-05-25 06:54:17
【问题描述】:
int client::add_user(item & item_in)
{
    char temp[ASIZE];
    cout << "\n\nEnter the name of your item: ";
    cin.get(temp, 100, '\n');
    cin.ignore(100, '\n');
    get_upper(temp);
    item_in.name = temp;

    cout << "\n\nEnter in effect one: ";
    cin.get(temp, 100, '\n');
    cin.ignore(100, '\n');
    get_upper(temp);
    item_in.effect1 = temp;

    cout << "\n\nEnter in effect two: ";
    cin.get(temp, 100, '\n');
    cin.ignore(100, '\n');
    get_upper(temp);
    item_in.effect2 = temp;

    cout << "\n\nEnter in effect three: ";
    cin.get(temp, 100, '\n');
    cin.ignore(100, '\n');
    get_upper(temp);
    item_in.effect3 = temp;

    cout << "\n\nEnter in effect four: ";
    cin.get(temp, 100, '\n');

    cout << "this";
    cin.ignore(100, '\n');
    cout << "that";

    get_upper(temp);
    item_in.effect4 = temp;

... 了解我确信这段代码有很多问题,我遇到的问题是前四个块运行得很好,但是当我使用 g++ 编译这段代码并运行它时,显示“this”,然后是分段错误没有“那个”。有什么想法吗?

【问题讨论】:

  • ASIZE的定义是什么?
  • @JoachimPileborg const int ASIZE = 30;
  • 您是否确定它在那里发生了段错误,而不是在系统开始刷新 cout 之前发生在其他地方(在此代码之后)的段错误? (尝试在“那个”之后添加 cout.flush() )。更好的是,使用调试器逐步完成它,它会准确地告诉你它失败的地方。
  • 关于@brepro 的评论,您也可以在调试器中运行程序来查找崩溃的位置。
  • item_in.name = temp 这样的几行是可疑的。 item_in.name 是什么?看起来您正在将临时数组的地址分配给变量。当函数返回并且数组超出范围时,这是一个问题。

标签: c++ arrays segmentation-fault cin


【解决方案1】:

根据您的另一个问题,看起来参数item_in 是一个具有多个char * 字段的结构。存在一个严重的问题,因为数组 temp 仅在此函数执行期间存在。您正在将临时数组的地址分配给item_in 中的指针。当函数返回时,数组超出范围,它的内存不再是你的。

您可以通过为指针分配内存并复制数据来解决此问题,但最佳解决方案是使用 C++ 标准库中的std::string。它按照您的预期处理资源管理和分配工作等操作。

【讨论】:

  • 不能使用字符串 :(。我最终只是将值直接分配到结构中,而不是使用中介。
猜你喜欢
  • 2021-08-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-25
相关资源
最近更新 更多