【问题标题】:Memory fault in C++ program seemingly caused by deque [closed]C ++程序中的内存错误似乎是由双端队列引起的[关闭]
【发布时间】:2014-02-12 02:25:56
【问题描述】:

我正在构建一个需要使用双端队列来管理一些动态数据的小型 C++ 程序。我构建了脚本并且当有少量数据放入和取出双端队列时效果很好,但是当放入和取出大量数据时,程序会因内存错误而出错。以下是相关代码:

  string curLine;

  deque<string> lineBuffer(context);
  int linesAfterContext = 0;

  ifstream newFile;
  istream *in;

  if (input == NULL) {
    in = &cin;
  }
  else {
    newFile.open(input);
    in = &newFile;
    if (newFile.fail() || !newFile.is_open()) {
      string error = "Not able to open that file. Please provide a valid file.";
      throw error;
    }
  }

  while(in->good()) {
    getline(*in, curLine);

    if (doesLineMatch(curLine)) {
      if (linesAfterContext == 0) {
        for (int i = 0; i < lineBuffer.size(); i++) {
          string curLineInBuffer = lineBuffer.at(i);
          if (!curLineInBuffer.empty()) {
            cout << lineBuffer.at(i) << endl;
          }
        }
      }

      cout << curLine << endl;

      linesAfterContext = context;
    }
    else {
      if (linesAfterContext > 0) {
        cout << curLine << endl;
        linesAfterContext--;
      }

      if (lineBuffer.size() == context) {
        lineBuffer.pop_front();
      }

      lineBuffer.push_back(curLine);
    }
  }

  if (input != NULL) {
    newFile.close();
  }

问题显然在于我如何推送和弹出双端队列,因为当我注释掉这四行时,内存错误不再发生。任何想法为什么这些行会泄漏内存?

编辑:

好的,我刚刚发布了完整的代码。我在原始代码中编辑了一些变量,没有考虑它们对内存管理方式的影响。我是 C++ 的新手(或任何经过验证的 C 语言 =P),所以我确信这是我的代码不是双端队列的问题。很抱歉造成混乱。

【问题讨论】:

  • 您确实需要显示您从示例中专门删除的代码。 “改变curLine”有什么作用? “做事”执行什么动作?由于curLine 是一个指针,我保证你正在用它做一些时髦的事情,这与使用deque 无关。
  • 专家设计的std::deque 没有内存泄漏。停止责备工具,并开始考虑您可能有错。内存泄漏出现在 您的 代码中。现在,发布一个测试用例。 :)
  • 你有deque&lt;string&gt; lineBuffer(context); 但你推lineBuffer.push_back(curLine); curline 是字符串*
  • 天哪,对不起@Krypton 和@paddy - 当我删除代码时,我将string 更改为string*(现在我想这是一个非常糟糕的主意)所以应该让事情变得完全不同。刚刚发布了完整的代码。我希望这更有意义......
  • @chromedude - 你也没有告诉我们什么是“输入”,它是否指向实际的有效内存等等(除了没有发布 dosLineMatch() 函数)。如果字符串有效,pop_front() 和 push_back() 没有任何问题。所以我的猜测是,你在某个地方破坏了内存,它以某种方式影响了双端队列操作,并且可能发生在你没有向我们展示的代码中。

标签: c++ memory-leaks deque


【解决方案1】:

来自您的 pastebin 链接,

http://pastebin.com/Jp1RgwqV

请查看您的 parseInt() 函数。您正在返回一个局部变量的地址,这是不行的。

int * parseInt(char *contextArg) {
  int resultingNumber = 0;
  //...
  int *endResult;
  endResult = &resultingNumber;
  return endResult;
}

看这里:

Returning local data from functions in C and C++ via pointer

我建议您更加熟悉指针,以及指针使用的注意事项。

【讨论】:

  • 我还建议在程序中的任何地方放弃使用 strlen() 或 C 字符串函数,以及“new char[whatever]”。在你的程序中不需要这个。实际上,程序中的任何字符串操作都可以使用 std::string 来完成。
猜你喜欢
  • 2021-05-06
  • 1970-01-01
  • 1970-01-01
  • 2020-10-15
  • 1970-01-01
  • 2010-12-24
  • 2020-04-11
  • 2016-09-15
  • 2010-12-28
相关资源
最近更新 更多