1

The program compile fine, but crashes when is running and shows this : Process terminated with status -1073741819

void reverse(char *str){

    char * end1 = str;
    char tmp = 'c';
    if(str){
        while(*end1){
            ++end1;
        }
        --end1;

        while(str<end1){
            tmp=*str;
            *str=*end1;
            *end1=tmp;
            str++;
            end1--;
        }
    }
}

Any idea ?

5
  • How are you calling reverse? Are you sure that the string you're passing is modifiable? I.e. not char* str = "foo";. Commented Mar 17, 2015 at 3:26
  • 2
    Guessing a string literal. Commented Mar 17, 2015 at 3:28
  • Yeah this function looks fine as is. You are likely calling it on illegal input. Commented Mar 17, 2015 at 3:28
  • not sure but have you used using namespace std; ? This might have collission with std::endl and char* endl Commented Mar 17, 2015 at 3:29
  • @Jagannath Nah, his is end1 not endl and even if it was, it would mask it due to being a locally declared variable. Commented Mar 17, 2015 at 3:30

1 Answer 1

2

There is absolutely nothing wrong with your reverse implementation: your code will work as long as the string that you pass is null-terminated and writable.

Then there must be something wrong with the way that you invoke it. The most common possibility is passing a string literal, writing to which is undefined behavior that may cause a crash:

char *s = "quick brown fox";
reverse(s); // <<== This would be undefined behavior

Demo of your working code.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks , i wasn't paying attention to the way i called the function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.