I am playing with array and pointer and got this segmentation fault. Can any one explain why I have been getting this segmentation fault in this code when I move my pointer "p" below "ptr" pointer in the code and when I comment out one of printf statement alternatively it disappears:
typedef struct str{
char* ptr;
}str_t;
copy(str_t t){
char a[12];
char *p; // <------ no error when move below ptr pointer
char *ptr;
printf("t= %s p = %d ptr = %d\n", t, p, ptr);
strcpy(a, t.ptr);
printf("a = %s %u\n", a, &a);
strcpy(ptr, t.ptr);
printf("ptr = %s %u\n", ptr, &ptr); //<--- comment it error disappears
p= t.ptr;
printf("p = %s %u",p, &p); //<--- comment it error disappears
}
int main ()
{
str_t t;
char app[] = "hello";
char ap[] ="world";
t.ptr = ap;
copy(t);
printf("%s\n", app);
return 0;
}
you can compile the code here to see the result : http://codepad.org/Q7zS8NaC
Thank you , for visiting this question .
strcpy(ptr, t.ptr)is copyingt.ptrto the location given byptrwhich hasn't been initializing. This results in undefined behavior which can be changed just by re-arranging code. If rearranging code makes a problem go away, that doesn't mean you don't have a problem. :)