Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Segmentation fault error

`I am trying to write a program that reverses two strings, I though I had it done pretty well but when I run it, the program runs till line 26, then I get a segmentation fault error. The program compiles fine. I am wondering if there is a simple or obvious problem in my functions that I am not seeing, Any help would be appreciated!!

Thanks in advance

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

// Reversing the characters in strings.

void reverse(string str);
void swap(char * first, char *last);

int main() {
    // declarations and initialization
    string str1;
    string str2;

    cout << "Please enter the first string of characters:\n";
    cin >> str1;

    cout << "Please enter the second string of characters:\n";
    cin >> str2;

    cout << "The strings before reversing are:" << endl;
    cout << str1 << " " << str2 << endl;

    // reverse str1
    reverse(str1);
    // reverse str2
    reverse(str2);

    // output
    cout << "The strings after reversing: " << endl;
    cout << str1 << " " << str2 << endl;

    return 0;
}

void reverse(string str) {
    int length = str.size();

    char *first = NULL;
    char *last = NULL;
    first = &str[0];
    last = &str[length - 1];
    for (int i = 0; first < last; i++) {
        swap(first, last);
        first++;
        last--;
    }
}

void swap(char *first, char *last) {
    char * temp;

    *temp = *first;
    *first = *last;
    *last = *temp;
}
like image 739
blaedj Avatar asked Dec 13 '22 07:12

blaedj


1 Answers

I don't know where line 26 is, but

char * temp;
*temp = ...

is not valid. temp should be pointed at a char, or (better yet) rewrite the function to where temp is a char.

Seth Carnegie observes that you'll have to pass the strings by reference if you want to modify the originals.

void reverse(string& str) { //pass by reference, so origional is modified
like image 141
Mooing Duck Avatar answered Dec 30 '22 10:12

Mooing Duck