Home Ask Login Register

Developers Planet

Your answer is one click away!

vitamike February 2016

reverse string bus error

I'm doing some basic c++ and decided to implement a revStr method.

But for some reason every time I execute the method, I get a bus error caused by the assignments in the while loop but I can't understand why.

Anybody got any clues? Any help would be much appreciated.

char* reverseStr(char* s){
        cout << "Void!"<<endl;
        return s;

    char* end, *start;
    end = s;
    start = s;

    while(*(end) != '\0'){

    while(start < end){
        char temp = *start;
        cout << temp <<endl;
        *start = *end;
        *end = temp;

    cout << "The reversed string is: " << s <<endl;
    return s;


Apologies.. I have added the driver program below:

int main(int argc, char** argv) {

assert(reverseChar("hello") == "olleh");

return 0;


BitWhistler February 2016

If you're passing a string literal it should not compile as your func (correctly) takes non-const. Unless, of course, you force cast it... so don't remove the const but strdup() it instead.

What could also be happening is that the loop runs forever. You can test it with a debugger.

The reason is that pointers cannot be properly compared for less, or greater then. Only for equality. You have to change your < to !=

DOUGLAS O. MOEN February 2016

Unable to reproduce problem ... code works as expected.

My Test (showing how I created "forwardCharStar[100]);")

int t282(void)
   std::string  forwardStr = "abcdefghijklmnopqrstuvwxyz";
   size_t sz =  forwardStr.size();

   assert(sz < 100); // check fit
   //          ^^^-----------vvv
   char      forwardCharStar[100];

   for (size_t i = sz-1; i < 100; ++i) forwardCharStar[i] = 0;
   for (size_t i = 0; i < sz; ++i)     forwardCharStar[i] = forwardStr[i];

   std::string rS = reverseStr(forwardCharStar);

   std::cout << "The reversed string is: " << rS << std::endl;

   return (0);

Note: filled tail of forwardCharStar[100] with '\0' - null terminator is important in c-style strings

Note: then transferred 26 chars from 'forwardStr' to front of forwardCharStar


The reversed string is: zyxwvutsrqponmlkjihgfedcba

Note: I commented out the char by char output from 2nd line of while loop

     // std::cout << temp << std::endl;

Note: forwardCharStar[100] matches the reversed string, the code modifies its input string.

Post Status

Asked in February 2016
Viewed 3,051 times
Voted 14
Answered 2 times


Leave an answer

Quote of the day: live life