-1
/*Reverse all strings with pointers in str*/
#include <stdio.h>
#include <string.h>
int main()
{
    char * str[] = {
                "To err is human...",
                "But to really mess things up...",
                "One needs to know C!!"
                };

    void xstrrev(char *);

    int i;
    for(i=0;i<3;i++)
        xstrrev(str[i]);

    for(i=0;i<3;i++)
        printf("%s\n", str[i]);

    return(0);
}

void xstrrev(char * s)
{
    int i = 0;
    char str[strlen(s)+1];
    while(*(s + i) != '\0')
        {
            str[i] = *(s + i);
            i++;
        }
    str[i] = '\0';

    i = 0; 
    while(*(s+i) != '\0')
    {   
        //printf("%c\t%c\n", *(s + i), str[strlen(s) -i -1]);
        *(s + i) = str[strlen(s) -i -1];
        i++;
    }   
}

When I compile with gcc (version 4.8.2 ) and debug with gdb (version 7.7.1) I get

Starting program: /home/aditya/Documents/Programming/C/strrev 

Program received signal SIGSEGV, Segmentation fault.
0x08048571 in xstrrev (s=0x8048620 "To err is human...") at strrev.c:39
39          *(s + i) = str[strlen(s) -i -1];

But I don't understand why. This has happened whenever I try to assign something using char pointers and while using array of pointers to strings. I tried uncommenting line the 5th last line and commenting the 4th last. I get the expected results without any error. Pls help.

adch99
  • 340
  • 1
  • 7

1 Answers1

0

The strings defined at compile-time are allocated in your code segment and can't be written to.

To achieve what you're trying to do you will need to allocate buffers for your strings using malloc, copy your strings there and reverse these buffers rather than the original string literals.

mephisto123
  • 1,400
  • 13
  • 38