I get this when I was trying something (just for understanding). Please explain this behavior:
First attempt:
void main()
{
char src[] = "vinay";
int i;
// char name[5] = "test";
char *name= "abcde";
printf("%s \n", name);
if (*(name+5) == '\0')
printf("6th char is null\n");
strcpy(name,src);
printf("printcheck \n");
for (i=0 ; i <6 ; i++)
{
printf("%c \n", *(name+i));
}
printf("%s \n",name);
}
Output:
abcde
6th char is null
zsh: 16644 segmentation fault (core dumped) a.out
Second attempt:
void main()
{
char src[] = "vinay";
int i;
char name[] = "pqrst";
//char *name= "abcde";
printf("%s \n", name);
if (*(name+5) == '\0')
printf("6th char is null\n");
strcpy(name,src);
printf("printcheck \n");
for (i=0 ; i <6 ; i++)
{
printf("%c \n", *(name+i));
}
printf("%s \n",name);
}
Output:
pqrst
6th char is null
printcheck
v
i
n
a
y
vinay
===========================================================================================
Question: Why does it crash on attempt 1? I was trying this on a Solaris machine Kernel version: SunOS 5.8 Generic 117350-43 Oct 2006