Solved

segmentation fault on fclose()

Posted on 2008-10-16
10
846 Views
Last Modified: 2012-05-05
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
Comment
Question by:mstrelan
  • 4
  • 4
  • 2
10 Comments
 
LVL 6

Accepted Solution

by:
mirzas earned 300 total points
Comment Utility
tempString = (char*)malloc(sizeof(char));


You need to allocate more here.


Try this as a test

 tempString = (char*)malloc(1024);
0
 
LVL 6

Expert Comment

by:mirzas
Comment Utility
...and you need to free the memory when you are done using it.
0
 
LVL 53

Assisted Solution

by:Infinity08
Infinity08 earned 200 total points
Comment Utility
>>         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
 
LVL 53

Expert Comment

by:Infinity08
Comment Utility
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
 
LVL 10

Author Comment

by:mstrelan
Comment Utility
wow so many comments. let me try them out
0
Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

 
LVL 53

Expert Comment

by:Infinity08
Comment Utility
Btw, note that :

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

1024 bytes might still not be enough, depending on the size of your file.
0
 
LVL 6

Expert Comment

by:mirzas
Comment Utility
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
 
LVL 53

Expert Comment

by:Infinity08
Comment Utility
>> 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
 
LVL 10

Author Comment

by:mstrelan
Comment Utility
@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
 
LVL 6

Expert Comment

by:mirzas
Comment Utility
Have fun.
0

Featured Post

Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

Join & Write a Comment

Suggested Solutions

Have you thought about creating an iPhone application (app), but didn't even know where to get started? Here's how: ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ Important pre-programming comments: I’ve never tri…
Preface I don't like visual development tools that are supposed to write a program for me. Even if it is Xcode and I can use Interface Builder. Yes, it is a perfect tool and has helped me a lot, mainly, in the beginning, when my programs were small…
The goal of this video is to provide viewers with basic examples to understand and use structures in the C programming language.
The goal of this video is to provide viewers with basic examples to understand and use conditional statements in the C programming language.

772 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

15 Experts available now in Live!

Get 1:1 Help Now