Solved

segmentation fault on fclose()

Posted on 2008-10-16
10
847 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
ID: 22729791
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
ID: 22729796
...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
ID: 22729799
>>         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
ID: 22729824
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
ID: 22729839
wow so many comments. let me try them out
0
Want to promote your upcoming event?

Attending an event? Speaking at a conference? Or exhibiting at a trade show? Easily inform your contacts by using a promotional banner in your email signature. This will ensure your organization’s most important contacts are in the know.

 
LVL 53

Expert Comment

by:Infinity08
ID: 22729849
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
ID: 22729875
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
ID: 22729922
>> 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
ID: 22729937
@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
ID: 22730178
Have fun.
0

Featured Post

Are your AD admin tools letting you down?

Managing Active Directory can get complicated.  Often, the native tools for managing AD are just not up to the task.  The largest Active Directory installations in the world have relied on one tool to manage their day-to-day administration tasks: Hyena. Start your trial today.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
using pointers to pointers to write to a two dimensional array 16 88
Passing command line arguments in C 10 85
Problem to show menu 5 87
Problem to save 10 150
This tutorial is posted by Aaron Wojnowski, administrator at SDKExpert.net.  To view more iPhone tutorials, visit www.sdkexpert.net. This is a very simple tutorial on finding the user's current location easily. In this tutorial, you will learn ho…
Summary: This tutorial covers some basics of pointer, pointer arithmetic and function pointer. What is a pointer: A pointer is a variable which holds an address. This address might be address of another variable/address of devices/address of fu…
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 how to create, access, and change arrays in the C programming language.

867 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

12 Experts available now in Live!

Get 1:1 Help Now