0

In this program, I used a recurrent function which is Strlen. However, prompt tells me that it is

zsh: 
segmentation fault  ./Strlen5

Does anyone know why it happens ?

My Code:

#include <iostream>
using namespace std;

size_t Strlen(char* str) {
    size_t i = 0;
    if (str[i] != '\0') {
        i += 1;
        return 1 + Strlen(str);
    } else {
        return 0;
    }
}

void ShowLength(char* str) {
    cout << "length:\"" << str << "\" : " << Strlen(str) << endl; 
}

int main() {
    ShowLength("Hello");
    ShowLength("Titan");
}
Gabriel
  • 763
  • 1
  • 10
  • 28
Shion Yamaguchi
  • 601
  • 2
  • 8
  • 16

2 Answers2

4

You never increment your pointer. You need to start one index ahead each time you recurse.

return 1 + Strlen(str + 1);

Also you should use const char* instead of char*

#include <iostream>
using namespace std;

size_t Strlen(const char* str) {
    if (str[0] != '\0') {
        return 1 + Strlen(str + 1);
    } else {
        return 0;
    }
}

void ShowLength(const char* str) {
    cout << "length:\"" << str << "\" : " << Strlen(str) << endl; 
}

int main() {
    ShowLength("Hello");
    ShowLength("Titan");
}

Working demo

Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
  • 1
    @Shion the i += 1 in the original was an attempt at that but does not work because you never use I and you dont pass I to the following iteration – pm100 Aug 25 '15 at 22:34
1

By the way the reason you got a segmentation fault is due to how a function call is constructed.

Since you need to pass on the stack the arguments and the pointer to next the instruction after the call you "waste" a portion of your stack every time you call a function (until you return). This usually is not a problem, but if you call an infinite number of function one after the other you face a stack overflow.

Further reading: Why infinite recursion leads to seg fault

Community
  • 1
  • 1
GalloCedrone
  • 4,869
  • 3
  • 25
  • 41