简体   繁体   中英

Segmentation fault when trying to copy elements of a string (C)

I am trying to work on a problem for school which requires me to reverse a string in place (among other things..). I have been struggling with this for awhile and am out of ideas.. here is my code:

void strRev(char*s)
{
    int i = 0;
    int length = strlen(s);
    char*rev = (char*)malloc((length+1)*sizeof(char));

    strcpy(rev,s);

    for(i;i<length;i++)
        s[i] = rev[length - 1 - i];

    printf("%s    %s",rev,s);
}

int main()
{
    char * test = "hello";
    strRev(test);
}

when I step through in Visual Studio, it hangs when it reaches the line inside the for loop. Unix gives me a segmentation fault. I know this must be something simple I'm missing, but I'm out of ideas and none of the answers online are helping.. And I'm running out of time.. Someone please enlighten me, what am I doing wrong?

Well, your code doesn't do it in place (else you wouldn't use malloc, also why are you using sizeof(char)?).

Try this:

void strRev(char*s)
{
    int i, len;
    char tmp;
    len = strlen(s);
    for(i = 0; i < (len >> 1); ++i)
    {
       tmp = s[len - 1 - i];
       s[len - 1 - i] = s[i];
       s[i] = tmp;
    }
}

And then modify you main() as the comments suggest.

test points to statically allocated buffer which must not be modified. And you do modify it by assigning s[i]=rev[...] . This causes segfault.

I think you wanted to write rev[i]=s[...] .

If you need to do it in place then allocate memory for "hello" dynamically ( strdup ) or on stack.

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