0

Possible Duplicate:
Why is this C code causing a segmentation fault?

I am writing a simple string reverse script.

I added print statements to debug. I keep getting a run time exception before Error1. But I can't seem to figure out the reason.

Here's my code:

#include <iostream>
#include <cstdlib>

using namespace std;

int strlen(char* s){ 
  int i = 0;
  while(*s != '\0'){
    i++;
    s++;
  }
  return i;
}

void reverse(char* src){

  char* dest = src+strlen(src)-1;
  char temp;

  while(src < dest){
    temp = *src;
    cout << "Error0" << endl;
    *src = *dest;
    cout << "Error1" << endl;
    *dest = temp;
    cout << "Error2" << endl;
    src++;
    dest--;
  }

}

int main (void){

  char* s = "Hello world";
  cout << s << endl;
  int i = strlen(s);
  cout << i << endl;
  reverse(s);
  cout << s << endl;

  getchar();
  return 0;
}

Here's my output:

            Hello world
            11
            Error0
Community
  • 1
  • 1
Tring Vu
  • 253
  • 1
  • 10
  • A string literal is not a `char*`, but because of old C details, compilers have to accept that anyway. Use `const char*` for any string literal, or you can initialize a `char s[]` array from a literal. – aschepler Dec 11 '12 at 00:47
  • Same question, same function, same error [Why is this C code causing a segmentation fault?](http://stackoverflow.com/questions/1614723/why-is-this-c-code-causing-a-segmentation-fault) – AnT stands with Russia Dec 11 '12 at 00:58

1 Answers1

3

this

char* s = "Hello world";

needs to be

char s[] = "Hello world";

Your orignal is trying to change constant memory that you aren't allowed to change, so you need to allocate space and initialize it with the string

Keith Nicholas
  • 43,549
  • 15
  • 93
  • 156