Segmentation Faults in C

Associate
Joined
28 Feb 2009
Posts
519
Whats the best way of debugging a segmentation fault. I know it is to do with the allocation of memory and i use malloc to allocate that memory but im stumped and have no idea. I have successfully allocated memory earlier on in my code.

I am useing the C gcc in Linux 32bit.
 
Cheers guys the problem that i have is that im reading a text file(of random size and length). Unfortunately this means that i am unable to use gdb as it can't open it so fails at the point of trying to open the file. I was more looking for general tips and tricks.

I'd love to upload the code to this or any other forum and ask for advice but its for my Uni coursework and there dead hot on copying exact code off the web. And i'd hate for them to find this forum and think that i lifted the code from here when Ive written it all myself.

Cheers for the help though :D
 
Im going to change a couple of variable names and upload the section that isnt working. That way maybe someone might be able to give me a slight pointer somwhere.

This is the code thats not working.
Code:
        currentline = ( char * ) malloc((size_t)msize);
	for(i = 0; i <= linecount; i++) /* linecount = varable used to no. lines */
	{
	currentline = strtok_r(fstring, "\n", &save1);
	while(currentline !=NULL)
	{	
		name = strtok_r(line," ",&save2);
		qu = atoi(strtok_r(NULL," ",&save2));
		pri = atoi(strtok_r(NULL," ",&save2));	
	}	
		pts[i].pname = malloc(strlen(name) +1 *sizeof(char));
		strcpy(pts[i].pname, name);
		pts[i].quan = qu;
		pts[i].pp = pri;
	}

Here are the variables and structure used.
	
	int linecount;

	typedef struct 
	{
		char *pname;
		int quan;
		int pri;
	} information;

	int qu;
	int pri;
	char *name;	
	char *currentline;
	char *save1;
	char *save2;

	information pts[linecount];
 
Yeah as far as i know it is possible to assign the array the value of linecounts as useing print statements i can prove this works.

The file is stored in fstring and looks as so
process21 2 1
process23 8 1
etc
Im tokenizeing each line then into three sections.

And as for the comments thats what i usually do but my lecture this year isnt a fan and says that comments are way over used and usually used when somone doesn't understand something properly so ive been trying to avoid them.
 
Last edited:
Back
Top Bottom