c++stringrecursioncrashinvalid-pointer

Why does finite recursive behaviour cause a crash ? (free(): invalid pointer)


Below is my code just a function called kk that will be recursively called for 10 times so impossible to cause stack overflow, but it crashes with

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

Who knows the reason??

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;
}

Solution

  • I guess you forgot to put the return keyword in the last line. By putting it, the code is working without errors

    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;
    }