【问题标题】:ncurses new_menu segmentation faultncurses new_menu 分段错误
【发布时间】:2013-05-01 16:10:36
【问题描述】:

我无法在 ncurses 中创建简单的文件选择。以下代码失败,valgring 说“条件跳转或移动取决于 main.cpp:122 中的未初始化值”

  // Create items 
  m_MenuItems = new ITEM * [ m_Files.size() + 1 ];

  int i = 0;
  for ( vector < CFile >::iterator it = m_Files.begin(); it != m_Files.end(); ++it, ++i ) {
    /* m_MenuItems[i] = new_item((*it).pName->c_str(), (*it).pDesc->c_str()); */
    m_MenuItems[i] = new_item("file", "size");
    cout << "[" << i << "]: " << (*it).pName->c_str() << ", " << (*it).pDesc->c_str() << endl;
  } m_MenuItems[++i] = NULL; // Item list has to be null terminated.

  // Create menu
  m_Menu = new_menu( (ITEM **)m_MenuItems ); // ! line 122
  cout << "Success" << endl;

输出就是这样:

[0]: main.cpp, 6888
                   [1]: a.out, 106798
                                     [2]: .., 4096
                                                  [3]: listdir.cpp, 701
                                                                       [4]: menu.cpp, 1908
                                                                                          [5]: ., 4096
                                                                                                      Segmentation fault (core dumped)

什么可能导致未启动的变量?

【问题讨论】:

  • new_item 返回什么?
  • 项目 *new_item(const char *name, const char *description);加上它在错误时返回 NULL。
  • 上面代码的第122行是哪一行?
  • @MichaelDorgan new_menu 行,如 cmets 中所述。
  • 我认为@MichaelDorgan 找到了您的问题。

标签: c++ segmentation-fault ncurses


【解决方案1】:

m_MenuItems[++i] = NULL 在你的 for 循环末尾会导致一个额外的“坏”条目被添加到你的列表中。您不需要 ++,因为 i 在退出循环时已经指向您最后一个条目的 1。

另外,如果new_item(...) 可以返回 NULL,您可能应该在分配到您的列表后检查它和break,因为如果我正确理解代码,它后面的任何项目都将被忽略。

【讨论】:

  • 现在可以完美运行。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-26
  • 1970-01-01
  • 1970-01-01
  • 2012-05-02
  • 1970-01-01
相关资源
最近更新 更多