Solved

segmentation fault on fclose()

Posted on 2008-10-16
10
850 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
PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

 
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
 
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

DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
shortest distance between a Line (p1(lat,long), p2(lat,long)) and a point p3(lat,long) 10 157
Binary Bomb: Phase 4 func4 3 326
Want to delete all my personal data 13 145
valid enum? 6 74
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…
This is a short and sweet, but (hopefully) to the point article. There seems to be some fundamental misunderstanding about the function prototype for the "main" function in C and C++, more specifically what type this function should return. I see so…
The goal of this video is to provide viewers with basic examples to understand how to use strings and some functions related to them in the C programming language.
Video by: Grant
The goal of this video is to provide viewers with basic examples to understand and use while-loops in the C programming language.

813 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