简体   繁体   中英

String reversal in C++ getting 'Segmentation fault (core dumped) error

This below gives me 'Segmentation fault (core dumped)' error after printing the reversed string. Can anyone explain why ?

#include <iostream>
#include <string>
#include <cstdio>

using namespace std;

void print (char *str) {
    if (*str) {
        print (str+1);
        cout << *str;
    }
}

int main() {
    char *str;
    cin >> str;
    print(str);
    cout << endl;
    return 0;
}

Uninitialized non-static local variables have an indeterminate value, and will in reality be seemingly random. Using them without initialization leads to undefined behavior , which is one of the most common causes of crashes.

The problem is that you have a pointer, but it doesn't point anywhere so when you use it to read input, the input stream cin will write to a random location in memory.

The solution is to not use character pointers for string, but the std::string class.


If you have to use pointers, then you have two solutions: Either declare the string as an array, or allocate memory using the new operator. However be cautioned that if you input more than you have allocated you will write out of bounds and once again have undefined behavior .

You have not allocated any memory to char *str . Try using char str[20] (20 is just an example, it could be anything as per your demand and your machine's capability) and everything will be fine. You are assuming that compiler will allocate memory for you but that's not the case. You are trying to access an unallocated memory or you can dynamically allocate them using malloc or new .

More than that you can use std::string to do get help from stl.

Either declare the str like char str[fixed_size] or use std::string. One of the simplest methods to do that might be this:

#include <iostream>
#include <string>
#include <algorithm>

using namespace std;

int main() {
    string str;
    cin >> str;
    reverse(str.begin(),str.end());
    cout <<str<< endl;
    return 0;
}

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