Program received signal SIGSEGV, Segmentation fault. C++

I'm getting this error (*s = *end; line) during debugging, while trying to reverse string using pointers. I'm using Windows 10 OS, codeblocks IDE and GDB debugger.

#include <stdio.h>
#include <string.h>
#include <limits.h>

void myreverse(char* s);

int main()
{
    char* s1 = "1234";
    myreverse(s1);
    printf("%s", s1);
    return 0;
}

void myreverse(char* s) {
    char tmp;
    char* end = s + strlen(s) - 1;

    for(; s < end; s++, end--) {
        tmp = *s;
        *s = *end;
        *end = tmp;
    }
}

Upvotes: 0

Views: 851

Answers (1)

Ted Lyngmo
Ted Lyngmo

Reputation: 117308

You should change s1 to char s1[] = "1234"; since you are making changes to the string.

Then in your myreverse() function, you never use the tmp variable, which makes your swap block failing.

Fixed:

#include <cstdio>   // use the C++ versions of the header files
#include <cstring>

void myreverse(char* s) {
    char tmp;
    char* end = s + std::strlen(s) - 1;

    for(; s < end; s++, end--) {
        // swap
        tmp = *s;
        *s = *end;
        *end = tmp;   // use tmp
    }
}

int main() {
    char s1[] = "1234";
    myreverse(s1);
    printf("%s", s1);
}

Note that the 3 lines in the swap block can be replaced with std::swap(*s, *end); and also that myreverse() can be completely replaced with std::reverse(std::begin(s1), std::end(s1));.

Upvotes: 1

Related Questions