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

11,746

Solution 1

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.

Solution 2

String literals like "abcd" are read only, you must not change them. Use

char string[] = "abcd";

instead.

Share:
11,746
Admin
Author by

Admin

Updated on June 05, 2022

Comments

  • Admin
    Admin almost 2 years

    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;
       }
    
  • zwol
    zwol almost 11 years
    You can initialize a char[] with a regular string literal and it'll still be writable. You don't have to write out the { 'a', 'b', 'c', 'd' }. (Unless you really don't want the terminating NUL, which does occasionally come up.)
  • Rafael
    Rafael over 6 years
    crazy enough, but I had no idea this was the case in C, thanks.