1

I'm trying to implement a simple string length function. If I write everything in main, the code segfaults. However, if I declare a strlen function, then it does not. Why is this happening?

Why does the following code work

using namespace std;
#include <iostream>

int strlen(char *s)
{
    char *p = s;
    while (*p != '\0')
        p++;
    return p - s;
}


int main()
{
    char *s;
    cin >> s;
    cout << strlen(s) << endl;
}

While this code segfaults?

using namespace std;
#include <iostream>

int main()
{
    char *s;
    cin >> s;
    char *p = s;
    while (*p != '\0')
        p++;
    cout << p-s << endl;
}
2
  • 3
    Both programs exhibit UB as s is a dangling (unallocated) pointer in both cases. It just so happens that one example appears to work while the other crashes. Commented Jan 9, 2014 at 7:49
  • 1
    Also, be careful with names like strlen. There is strlen from string.h or cstring, std::strlen from cstring, any of which might get included by other std library headers. So better put your function inside a namespace. Commented Jan 9, 2014 at 7:52

1 Answer 1

4

You haven't allocated any memory for s. The reason it works in one case and not the other is likely because of the wonders of undefined behavior in C++.

Sign up to request clarification or add additional context in comments.

1 Comment

strikethrough "likely"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.