简体   繁体   中英

Who can explain this recursive function in my CPP program?

I want to use recursive fuction to print the element in vector, here are right answer:

#include <iostream>
#include <vector>
using namespace std;

void print(vector<int> vInt, unsigned index) {
    unsigned sz = vInt.size();
    if (!vInt.empty() && index < sz) {
        cout << vInt[index] <<endl;
        print(vInt, index + 1);
    }
    
}

int main() {
    vector<int> v = {1, 3, 5, 7, 9, 11, 13, 15};
    print(v, 0);
    return 0;
}

It can run successfully. But at the beginning I just make one mistake, only a little difference, I put print out the if loop, and I use " " to replace endl , it's just like this:

void print(vector<int> vInt, unsigned index) {
    unsigned sz = vInt.size();
    if (!vInt.empty() && index < sz) {
        cout << vInt[index] <<" ";
    }
    print(vInt, index + 1);
}

And make is okay, but when I use ./main to run it, it report an error:

❯ ./main
[1]    2913 segmentation fault (core dumped)  ./main

Can one explain the reason please?

In the second case, the recursive function call is not guarded by the if -statement. That's important. That checks if there are further elements to process, and only recurses if there is more data to access . If you put the recursive call outside the if , it will always execute, regardless of whether the array is actually empty. In other words, you're definitely going to run off the end of your array here, thus the segfault.

By the way -- this could be really easily found with a debugger. For things like segfaults, a debugger is the first tool you should turn to.

I just make one mistake, only a little difference

小动作

In the second case you have Undefined Behavior since will go out of bounds as the recursion never ends.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM