A string literal in your code is typically placed by the compiler into a read-only section of your program's memory space. When you assign testy2 = " THING! ";
, you're setting testy2
to point to a string literal in static "read-only" memory. Then when you call strstrip()
to modify that memory, you get a SIGSEGV, or whatever your platform calls it, at the point that strstrip()
tries to write the nul char ('\0'
) because you can't write to memory whose attributes are set to "read-only". To get a copy of that string literal that you can modify, you could use strcpy()
to make a copy of it, and call strstrip()
on that copy. Of course to make a copy of it, you have to copy it into memory you own, which you could get from malloc(strlen(testy2)+1)
or new char[strlen(testy2)+1]
, or as you've done in your original post, by creating a local allocation.
One thing to note is that strstrip()
both 1) returns a pointer that may be different from the passed-in pointer, and 2) may alter the string at the memory passed to it. In your example, you're losing the returned pointer because you didn't assign it to anything... which isn't all that bad because you can get the same pointer address back by simply calling strstrip()
on the original pointer again, but that would be a little inefficient if you needed the stripped string more than once. But be careful here... if you used malloc()
or new
to dynamically allocate space for your copy of the string literal (and assigned the returned address to a pointer, let's say testy2
), then don't assign the return of strstrip() to that pointer, or else you can't later use the pointer to free the dynamically allocated memory! When you call free()
or delete
, you need to pass it the original pointer you got from malloc()
or new
, not the pointer you got back from strstrip()
.