0

I am dealing with a code in C about pointers. I want to describe the issue with a code making this clear.

#include<stdio.h>
#include<string.h>
int main(){
    char *ptr="hello";
    printf("%s",ptr);
    *(ptr+0)='a';
    printf("%s",ptr);
    getchar();
    return(0);
}

When i run the code giving segmentation fault error. Try to access the data indirect way but now giving the error. I am a little confused now. What would be the reason. Platform is Ubuntu 21.10. Compiler is gcc. I would be much appreciated.

synapsis
  • 15
  • 2
  • 2
    Your `ptr` points to an element of a string literal. Attempting to modify a string literal, as your code therefore does, produces undefined behavior. A segfault is not surprising under the circumstances. – John Bollinger Feb 28 '23 at 20:00

0 Answers0