-1

When i pass the char * literal to trim() it seg faults but when I send an array pointer it works why is this not working?

int main(void){
    /* If instead I have a char s[100] = "Hi      "; 
     * it works as intended so why does it not work when i pass this.*/
    char *s = "Hi       ";
    printf("<%s>\n", s);

    trim(s);
    printf("<%s>\n", s);

}

/* Trims all white-space off at end of string. */
void trim(char *s){
    while (*s != '\0') ++s;

    --s;
    while (*s == ' ') --s;
    *(++s) = '\0';
}
kron maz
  • 131
  • 1
  • 6

1 Answers1

4

Modifying contents of string literals is undefined behavior in C, which means it can lead to any kind of misbehavior, including crashes. Conceptually a string literal is cost char *, but for historical reasons its type is non-const. This means that assigning a string literal to a char * variable compiles without error, but a program that actually writes there is not a valid C program.

The immediate cause of the crash is that the compiler chose to place string literals in read-only memory. Such memory is guarded by the OS and a program that tries to modify it is automatically terminated.

user4815162342
  • 141,790
  • 18
  • 296
  • 355
  • That's obviously correct for the system in question. Sometimes, though, you can get away with modifying string literals (you might try on vxWorks previous to 7.0...). The important bit of information missing in this answer is that doing so is undefined behaviour... – Aconcagua Apr 20 '18 at 06:18
  • @Aconcagua Good point, I've now amended the answer. – user4815162342 Apr 20 '18 at 06:43