Code:
#include "stdio.h"
#include "string.h"
int main()
{
char *p = "abc";
printf("p is %s \n", p);
return 0;
}
Output:
p is abc
Code:
#include "stdio.h"
#include "string.h"
int main()
{
char *p = "abc";
strcpy(p, "def");
printf("p is %s \n",p);
return 0;
}
Output:
Segmentation fault (core dumped)
Could someone explain why this happens?
Because p is pointing to read only memory.
Overwriting data that p points to results in undefined behavior.
A string literal is any string you specify explicitly in quotes. All string literals are read only. (Note: You can use a string literal to initialize a char array.)
You need to instead allocate your own buffer like this: