1

The following program is throwing segmentation fault.

#include<stdio.h>

int main(){
    char *p = "exs";
    char x;
    x = (*p)++;
    printf("%c\n",x);
    return(0);
}

Please help.

I was expecting 'f' but got seg fault.

  • 2
    `*p` points to `'e'` in the string literal `"exs"`, `++` tries to change it, which is not allowed for string literals, because they are usually in the read-only memory block. You will get your expected result by changing the line to `x = *p + 1;`, which only increments a copy of the string literal element. – mch Apr 03 '23 at 07:31
  • 2
    "I was expecting 'f'" Why would you expect `'f'`? The postincrement operator `(*p)++` increments the value after it is evaluated. Even if `p` would not point to a string literal which mustn't be modified, you would never get `'f'`. That said, trying to modify the string literal causes undefined behavior which end in the segfault in your case. – Gerhardh Apr 03 '23 at 07:31

1 Answers1

0

You need to copy the string into writeable memory first using strdup. Then use ++(*p) instead of (*p)++ to get the value after incrementing the first byte. Although not necessary in short-lived processes, it is a good style to free() the memory allocated with strcpy() when it is not used to avoid memory leaks.

With these changes applied, the program would look like this:

#include<stdio.h>
#include<string.h>
#include<stdlib.h>

int main(){
    char *p = strdup("exs");
    char x;
    x = ++(*p);
    printf("%c\n",x);
    free(p);
    return(0);
}
tla
  • 855
  • 1
  • 14