tags:

views:

174

answers:

3

Here is my code:

    void reverseStr(char *str)
{
    if (str == NULL) return;
    int i=0, j=strlen(str) -1;
    while(i<j)
    {
        char temp = str[j];  //i think this is the cause of the problem
        str[j] = str[i];
        str[i] = temp;
        i++;
        j--;
    }
}

So here is where it is called:

int main()
{   
    char *str = "Forest Gump";
    reverseStr(str);
    cout << str;
}

Here is my error: /Applications/TextMate.app/Contents/SharedSupport/Bundles/C.tmbundle/Support/bin/bootstrap.sh: line 7: 1931 Bus error "$3".out

Any thoughts? Thanks in advance.

+4  A: 

String literals are read only memory, you can't reverse them, nor modify them in any way without encountering undefined behavior.

Copy your string into a buffer first, then pass in the buffer. Or declare an array instead of a pointer and initialize that array with a string initializer.

Brian R. Bondy
No, since `i > j` in that case
palswim
@palswim: I changed my answer I realized that right after I posted it.
Brian R. Bondy
in fact, on Linux with gcc, it SIGSEGVs on the line str[j] = str[i]; (where i = 0 and j = 10).
Andre Holzner
@Brian: Yeah, I was about to post the same "answer" right when you did before I realized that the strlen() == 0 error case wouldn't cause problems.
palswim
A: 

The error is in a bash/shell script not in your program. Would you please post the bash script also?

schoetbi
+8  A: 

Str pointes to a fixed string. You are modifying it in place. In other words, you trying to change the text literal. Try this:

char *str = strdup("Forest Gump"); 
reverseStr(str); 
cout << str; 
free(str);
James Curran
Or just `char str[] = "Forest Gump";` removing the need to memory allocation and management.
TheUndeadFish