user3176509
user3176509

Reputation: 13

Segmentation fault when searching for the end of a string in main, but not in a function C++

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

Upvotes: 1

Views: 75

Answers (1)

dandan78
dandan78

Reputation: 13854

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++.

Upvotes: 4

Related Questions