0

I am trying to write a simple reverse string program and getting the above error. I am unable to understand what I'm doing wrong.

void reverse(char *str) {
char *end, *begin;
end = str;
begin = str;

while (*end != '\0') {
    end++;
}

    end--;

char temp;

while (begin < end) {
    temp = *begin;
    *begin++ = *end; //This is the line producing the error
    *end-- = temp;
}
}

void main() {
char *str = "welcome";
reverse(str);
}

Need your help. Thanks.

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
Czar Inga
  • 3
  • 2

1 Answers1

1

You are attempting to modify a string literal, which is undefined behavior. This would be a valid way of declaring str in main if you wanted to modify it:

char str[] = "welcome";

Also, you are assigning end to the beginning of str and then you are doing this:

end--;

which decrements the pointer to before the memory allocated for the string, which is undefined behavior. My guess it you meant to do this:

end = str+ (strlen(str)-1);
Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740