![](/img/trans.png)
[英]Why does calling free () on a pointer allocated with 'new' cause heap corruption?
[英]Why does finite recursive behaviour cause a crash ? (free(): invalid pointer)
下面是我的代码只是一个名为 kk 的函数,它将被递归调用 10 次,因此不可能导致堆栈溢出,但它会崩溃
`./3' 中的错误:free():无效指针: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;
}
我猜你忘了把 return 关键字放在最后一行。 通过把它,代码工作没有错误
string kk(string &s)
{
static int i=0;
s+="q";
i++;
cout<<"i="<<i<<endl;
if(i>=10) return s;
return 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.