简体   繁体   中英

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

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)); .

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