Possible Duplicate:
Why do I get a segmentation fault when writing to a string?
I have the following program:
#include <iostream>
using namespace std;
void reverseString(char* first, char* last)
{
while(first < last)
{
cout << *first << " " << *last << endl; //for debugging; prints 'H' and 'o' then crashes
char temp = *last;
*last = *first; //this line crashes the program
*first = temp;
first++;
last--;
}
}
int main()
{
char* s = "Hello";
reverseString(s, s + strlen(s) - 1);
cout << s << endl;
}
However, I'm having trouble swapping the values to which the pointers point. I thought *p = *p1 should just set the pointed-to value of p to the pointed-to value of p1, but something seems bugged up. Thanks in advance for any help!
The code looks fine to me. The most likely problem is that the compiler is allowed to assume that string literals are not modified, so it can put them in read-only memory. Try
char s[] = "Hello";
in main()
instead, which creates a writable copy of the string literal.
An alternative solution to @j_random_hacker:
char* buffer = new char[32];
strcpy(buffer, "Hello");
reverseString(buffer, buffer + strlen(buffer) - 1);
... rest of your program ...
delete[] buffer;
This properly allocates memory for a C-style string which can then be modified by any function. Of course, you need to include <string.h>
header to access strcpy
and strlen
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With