4

Possible Duplicate:
Getting Segmentation Fault

/*  Reverse a string in place
 */
#import <stdio.h>

void reverse(char * str);

int main()
{
    char * string = "This is a string.";
    printf("%s\n", string);
    reverse(string);
    printf("%s\n", string);
}

void reverse(char * str)
{   
    char * start = str;
    char * end = str;
    if(0==*str)
        return;

    //Find the end
    for(;0 != *(++end););

    end--;
    do
    {
        *end   = *end ^ *start;
        *start = *end ^ *start;
        *end   = *end ^ *start;
    }while(++start < --end);
}

I'm not sure why this seg faults. Is is because I'm initializing my char * with a constant string?

Community
  • 1
  • 1
Joshua Olson
  • 3,675
  • 3
  • 27
  • 30

1 Answers1

6

You are trying to modify a string constant. Replace:

char * string = "This is a string.";

with

char string[] = "This is a string.";

to remedy that.

Michael Foukarakis
  • 39,737
  • 6
  • 87
  • 123