0
#include<stdio.h>
int main()
{
char *c;
c = "hello";
c = "name";
return 0;
}

The above code compiles fine but below gives seg fualt at run time

#include<stdio.h>
int main()
{
char *c;
c = "hello";
*c = 'A';
return 0;
}
  • 2
    You can't modify string literals, which is what `c` points to. Try using the string literal to initialize an *array*, instead of a pointer: `char c[] = "hello";`' – Steve Summit Aug 25 '19 at 11:01
  • ok but why the above code works. There we are modifying it other name...? – MustansirD Aug 25 '19 at 11:12
  • Many answers [here](https://stackoverflow.com/questions/164194), including a link to the [old C FAQ list answer](http://c-faq.com/decl/strlitinit.html). – Steve Summit Aug 25 '19 at 11:18
  • @MustansirD because the first example is pointing `c` to somewhere else, it's not modifying the existing string. – Federico klez Culloca Aug 25 '19 at 11:23
  • Understood Thanks everyone. Can anyone help with a program and a tool like nm in linux to check in which memory the variables occupy the space like stack heap data seg and code seg...? – MustansirD Aug 25 '19 at 11:49

0 Answers0