• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 870
  • Last Modified:

segmentation fault on fclose()

The following method below is meant to read a file, print some info to the screen and then close the file. For some reason the call to fclose(fp) causes a Segmentation Fault. Any ideas why? I have tried checking if fp == NULL and it doesnt
/**
 * Reads a text file in to a string
 */
int readFile(char* filename) {
 
	FILE *fp;
	
	char ch;
	char* tempString;
 
	int i = 0;
 
	if((fp=fopen(filename,"r"))==NULL) {
		printf("Cannot open file.\n");
		exit(1);
	}
 
	tempString = (char*)malloc(sizeof(char));
 
	while((ch=fgetc(fp)) != EOF) {
		if (ch == '@') {
			if (sizeof(tempString) > 0) {
				tempString[i++] = '\0';
			}
			printf("string: %s\n", tempString);
			bzero(tempString, sizeof(tempString));	
			i = 0;
		} else if (ch == '\n') {
			;
		} else {
			tempString[i++] = ch;
		}
	}
 
	tempString[i++] = '\0';
	printf("string: %s\n", tempString);
 
	/* this causes segmentation fault? */
	fclose(fp);
	
    return 0;
}

Open in new window

0
mstrelan
Asked:
mstrelan
  • 4
  • 4
  • 2
2 Solutions
 
mirzasCommented:
tempString = (char*)malloc(sizeof(char));


You need to allocate more here.


Try this as a test

 tempString = (char*)malloc(1024);
0
 
mirzasCommented:
...and you need to free the memory when you are done using it.
0
 
Infinity08Commented:
>>         tempString = (char*)malloc(sizeof(char));

allocates memory for only one character. You'll need to allocate sufficient memory for the amount of characters you intend to place in the tempString.
0
The IT Degree for Career Advancement

Earn your B.S. in Network Operations and Security and become a network and IT security expert. This WGU degree program curriculum was designed with tech-savvy, self-motivated students in mind – allowing you to use your technical expertise, to address real-world business problems.

 
Infinity08Commented:
Btw, the segmentation fault is not caused by the fclose, but by one of the lines that adds a character to the tempString.

Also :

>>                         bzero(tempString, sizeof(tempString));

You shouldn't use sizeof here. sizeof(tempString) will return the size of the tempString pointer (usually 4 on 32bit systems), and not the size of the memory block that tempString points to.
The same is true for the other uses of sizeof.


>>         while((ch=fgetc(fp)) != EOF) {

fgetc returns an int value, with EOF being a special value. If you want to compare to EOF, you should use an int type for ch.
But instead I'd advise to use feof to check whether the end of the file is reached :

        http://www.cplusplus.com/reference/clibrary/cstdio/feof.html
0
 
mstrelanAuthor Commented:
wow so many comments. let me try them out
0
 
Infinity08Commented:
Btw, note that :

>>  tempString = (char*)malloc(1024);

1024 bytes might still not be enough, depending on the size of your file.
0
 
mirzasCommented:
I suggested 1024 as a test. Thank you for pointing it out.

Anyway I do not see the code trying to load the entire file into tempString.

I think it looks for user part of e-mail accounts. :(
Are you up to something bad?
0
 
Infinity08Commented:
>> Anyway I do not see the code trying to load the entire file into tempString.

You're right, I did not notice that 'i' was reset to 0 after one was found.
0
 
mstrelanAuthor Commented:
@mirzas

no definitely not up to anything bad. i am doing a uni assignment and i have no idea why they have provided the file in the way it is. but anyway the goal is to make a dictionary lookup kind of service. the dictionary is provided like this

@some-word@n. the definition of the word goes here
@another-word@n. another definition goes here

anyway, setting the allocation size to 1024 has worked fine, and basically i've set a constant called MAX_LINE_LENGTH preventing the program from trying to read more than 1024 characters in the line

mirzas was first to directly answer my question but your input infinity08's input has definitely been helpful. thanks guys for being so quick
0
 
mirzasCommented:
Have fun.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Improve Your Query Performance Tuning

In this FREE six-day email course, you'll learn from Janis Griffin, Database Performance Evangelist. She'll teach 12 steps that you can use to optimize your queries as much as possible and see measurable results in your work. Get started today!

  • 4
  • 4
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now