-
Seg- faults
Hmm.. Something tells me I have to get back to K&R this weekend. Found a similar question in some C aptitude test , Not able to explain why it segfaults ..
Code:
# include<stdio.h>
# include<string.h>
# include<stdlib.h>
struct ping{
char *name;
int len;
};
struct ping hunt1;
struct ping *hunt2;
int main()
{
char *test1;
test1=malloc(sizeof(char)*10);
printf( " enter some string <10 chars \n");
scanf("%s",test1);
printf(" test1 =%s\n",test1);
printf(" len test1 =%d\n",strlen(test1));
hunt1.name=test1;
printf("hunt1.name = %s\n",hunt1.name);
hunt1.len=strlen(test1);
printf("hunt1.len = %d\n",hunt1.len);
strcpy(hunt2->name,test1);
//hunt2->name=test1;
printf("hunt2->name = %s\n",hunt2->name);
hunt2->len=strlen(test1);
printf("hunt2->len = %d\n",hunt2->len);
return 0;
}
output :
Code:
enter some string <10 chars
asdf
test1 =asdf
len test1 =4
hunt1.name = asdf
hunt1.len = 4
Segmentation fault
-
hunt2 is not initialized pointer (due to global var - it is null pointer) you cannot dereferense it without allocating space first
-
> Join Date: Jun 2006
> Posts: 279
Still working on the idea of indentation then I see :rolleyes:
-
FYI :
That was not even my code...
I did write this one : http://cboard.cprogramming.com/showthread.php?t=90558