Thread: segmentation fault

  1. #1
    Registered User
    Join Date
    Oct 2008
    Posts
    30

    segmentation fault

    i have a data.raw file whose contents are
    4
    8 register
    5 fine
    3 afda
    4 asd

    all i was supposed to do is to copy the names into a structure array here is the code i have written which is showning segmentation fault on exectution
    Code:
    struct extract
    {
    	int p_num;
    	int p_len;
    	char *data;
    };
    int main(int argc , char * argv[]){
    	FILE *fp;
    	int n,i;
    	struct extract *e;
    	fp=fopen("data.raw","r");
    	fscanf(fp,"%d",&n);
    	e=(struct extract*)malloc(n*sizeof(struct extract));
    	e[0].p_num=n;
    	for(i=1;i<=n;i++){
    	fscanf(fp,"%d %s",&e[i].p_len,e[i].data);
    	printf("%d %s\n",e[i].p_len,e[i].data);
    	}
    	
    	return 0;
    }

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    > for(i=1;i<=n;i++)
    An array of n slots has 0 to n-1 as subscripts.
    You're running off the end by 1 step.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    You're also not allocating any space for each e[i].data either.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  4. #4
    Registered User
    Join Date
    Oct 2008
    Posts
    30
    thanks salem..
    it solved the problem

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Segmentation fault problem
    By odedbobi in forum Linux Programming
    Replies: 1
    Last Post: 11-19-2008, 03:36 AM
  2. Segmentation fault
    By bennyandthejets in forum C++ Programming
    Replies: 7
    Last Post: 09-07-2005, 05:04 PM
  3. Segmentation fault
    By NoUse in forum C Programming
    Replies: 4
    Last Post: 03-26-2005, 03:29 PM
  4. Locating A Segmentation Fault
    By Stack Overflow in forum C Programming
    Replies: 12
    Last Post: 12-14-2004, 01:33 PM
  5. Segmentation fault...
    By alvifarooq in forum C++ Programming
    Replies: 14
    Last Post: 09-26-2004, 12:53 PM