【问题标题】:C++ Run-Time Check Failure #2 - Stack around the variable 'theArray' was corruptedC++ 运行时检查失败 #2 - 变量“theArray”周围的堆栈已损坏
【发布时间】:2014-04-08 20:57:20
【问题描述】:

这实际上是我第一次在这个网站上发帖。我在使用 ctsrings 时遇到问题。这个函数的目的是定义我自己版本的 strcat 函数。 我的代码:

void mystrcat(char destination[], const char source[])
{

    int i = 0;
    while (destination[i] != '\0')
    {
        ++i;
    }

    int w = 0;
    while (source[w] != '\0')
    {
        ++w;
    }

    int numOfElements = i;
    int q = 0;
    while (q < w)
    {
        destination[numOfElements] = source[q];
        ++q;
        ++numOfElements;
    }

    i += q;


    for (int c = 0; c < i; ++c)
    {
        cout << destination[c];
    }


}

由于某种原因,每当我使用两个随机 cstrings 价格(例如,“cdvfvf”和“gfgfgd”)运行我的程序时,程序确实会输出正确的组合答案,但之后它会给我“损坏堆栈”围绕数组错误。同样,如果我对代码目的或问题的描述没有意义,真的很抱歉。并感谢任何回复的人。

【问题讨论】:

  • “损坏的堆栈”意味着您在 97% 的时间里写入了一个距离数组末尾太远的索引,而 3% 的时间您写入了索引 -1。 Ergo "destination[numOfElements] = source[q];" 是你的错误。
  • 显示调用函数的程序部分。
  • 包含变量“theArray”的代码部分是相关的。
  • @user3512751 - 如果来自莫斯科的弗拉德给出的答案是正确的,那么不管你信不信,你的代码没有任何问题。代码按设计工作,因为 strcat() 的工作方式相同。你给 strcat() 一个短的目标缓冲区,程序可能会以同样的方式崩溃。
  • @PaulMcKenzie strcat 添加了最后的'\0',但他的代码没有。

标签: c++ runtime-error


【解决方案1】:

我认为问题在于数组destination不够大,无法存储连接的字符串。

例如,对于这些字符串文字 "cdvfvf""gfgfgd",目标数组的大小必须至少等于 13。

还要考虑到这个循环之后:

while (q < w)
{
    destination[numOfElements] = source[q];
    ++q;
    ++numOfElements;
}

应该有

destination[numOfElements] = '\0';

【讨论】:

  • 好的。我试试看
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-21
  • 2013-12-13
  • 2013-12-10
  • 2015-02-09
  • 2015-05-24
相关资源
最近更新 更多