C function to swap two chars in a char[] segfaults, despite not working with string literals

c, string, swap

Solution

char *string = "abcd";

is a pointer to a string literal and string literals are immutable in C. Modifying a string literal invokes undefined behavior.

Change the declaration of `string` to:

char string[] = "abcd";

to fix you program. Here `string` is an array, initialized with the content of a string literal and is modifiable.

Problem

I've verified in GDB that the program crashes on the *(a) = *(b) line. This does not make sense to me. In my main function I allocated a 5 bytes for the char* string. I pass two pointers to swap, one is string offset by sizeof(char) and the other is the pointer to string. These pointers are copied to swap()'s call stack. The 5 bytes I allocated earlier should still be on the stack so swap() should have no problem with dereferencing and writing to those locations on stack, right? ``` int main(int argc, char* argv[]) { char *string = "abcd"; swap((string+1), string); printf("%s\n",string); return 0; } void swap(char *a, char *b) { if(!a || !b) return; char temp = *(a); *(a) = *(b); *(b) = temp; } ```

Original source