c++ - 为什么有限递归行为会导致崩溃? (free():无效的指针)

标签 c++ string recursion crash invalid-pointer

下面是我的代码,只是一个名为kk的函数,它将被递归调用10次,因此不可能导致堆栈溢出,但是会崩溃

Error in `./3': free(): invalid pointer: 0x0000000000602100



谁知道原因?
string kk(string &s)
{
    static  int i=0;
    s+="q";
    i++;
    cout<<"i="<<i<<endl;
    if(i>=10) return s;
    kk(s);
}

int main()
{
    string s="wer";

    cout<<"s="<<kk(s)<<endl;
}

最佳答案

C26444 NO_UNNAMED_RAII_OBJECTS ,这是引起问题的原因。
每次返回时,都会创建并删除该临时对象。

修改如下代码:

#include <iostream>
#include <cstdlib>

static  int i = 0;

void kk(std::string& s)
{

    s += "q";
    i++;
    std::cout << "i=" << i << std::endl;
    if (i >= 10) return ;
    kk(s);
}

int main()
{
    std::string s = "wer";
    kk(s);
    std::cout << "s=" << s << std::endl;
}

输出:

i=1 i=2 i=3 i=4 i=5 i=6 i=7 i=8 i=9 i=10 s=werqqqqqqqqqq

关于c++ - 为什么有限递归行为会导致崩溃? (free():无效的指针),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60585971/

相关文章:

python:将 'backslash double-quote'字符串写入文件

比较字符串的长度 C

Java String.split(),如何防止新数组中出现空元素

haskell - Haskell 中 Hangman 的错误递归

javascript - 奇怪的 JavaScript 行为(我期待递归)

递归时Haskell Print?

c++ - Blynk.syncVirtual(V1)不更新虚拟引脚值

c++ - 如何在 Gui win32 编程中使用静态标签和按钮

java - 为什么不能创建没有花括号的 1 语句函数?

c++ - QT QTextBrowser 左键单击时禁用写入位置