-2

Possible Duplicate:
How to reverse a string in place in c using pointers?

I was trying to reverse a string using C. A segmentation fault occurs. Any idea why?

Here's my code:

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

    int main(void)
    {
    char *str1 = "abbd";
    char *str2;


    str2 = str2 + strlen(str1)-1;

    while(*str1 != '\0')
    *(str2--) = *(str1++);


    printf("%s", str2);

     return 0;
    }
Community
  • 1
  • 1
qwr qwr
  • 1,049
  • 4
  • 22
  • 46
  • Even if you figure out the segmentation fault, it's not going to change the string. Can you figure out why? – kindall Mar 31 '12 at 01:15
  • Even if you fix the bug everybody's pointed out to you, it's impossible to modify your string in place because that string is non-modifiable. You cannot modify string literals. – R.. GitHub STOP HELPING ICE Mar 31 '12 at 01:31

4 Answers4

0

Looks like you didn't allocate any space for str2, just made the pointer.

Cameron
  • 1,675
  • 11
  • 12
0
char *str2;
str2 = str2 + strlen(str1)-1;

You declared a pointer str2, but initialize its value to garbage. (str2 + ...)

Are you trying to do an in-place modification? That won't work for this code, the char *foo="bar"; format places the "bar" in a write-protected memory space on platforms that support it.

Are you trying to do an out-of-place modification? If so, you forgot to allocate that space.

sarnold
  • 102,305
  • 22
  • 181
  • 238
0

You're not allocating memory for str2.

str2 = (char *)malloc(sizeof(char) * (strlen(str1) + 1));

I haven't tried it, but it seems like you're going to want to set str2 = str2 + strlen(str1), otherwise I think you'll run off the "front" of your str2 buffer as well.

I would recommend treating your strings as arrays, and let the compiler do the pointer arithmetic for you.

That Chuck Guy
  • 443
  • 4
  • 12
0

Nothing's properly allocated (allocate the proper length at declaration or malloc it) and you don't really move through the strings and check for the end of your condition as fitted (try str[i]). You have awaken the kraken.

Vincent L.
  • 122
  • 3