Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Segmentation error

Status
Not open for further replies.

stevebiks

Programmer
Feb 13, 2005
10
US
Okay i am trying to get this file reading thing to work, and so far i am failing misserably. i am getting the "segmentation fault" error, which has to do with my char array i figure, but i have played with it in every way that i know how and i can't get it to work correctly. can anyone give me any advice here to point me in the right dirrection or tell me what i am missing?

thanks a lot for your time and help!!!

#include <stdio.h>


int main()
{
int inFile, outFile;
FILE *stream;
FILE *ostream;
int numread, numwritten;

char *s;
s=(char*) malloc(10000); memset(s,0,10000);

char outFileName[]="out_test";
char InFileName[]="in_test";

/*writeable file*/
ostream = fopen(outFileName, "w");
stream=fopen(InFileName, "r");

/*read from a file,copysize to numread*/
numread=fread(s,1,9999,stream);

/*write to file*/
fwrite(s,1,numread,ostream);

/*close files*/
int fclose(FILE *stream);
int fclose(FILE *ostream);

}
 
Code:
s=(char*) malloc(10000);
Don't cast the return value of malloc. Include <stdlib.h> in the first place and you won't get a warning and feel the need to cover it up with the cast, which can be dangerous.


Code:
numread=fread(s,1,9999,stream);
Why only 9999? You allocated one more byte than that, so you might as well use it, too.


Code:
/*close files*/    
int fclose(FILE *stream);        
int fclose(FILE *ostream);
This is just declaring a function twice (which you shouldn't do, since it's already declared in stdio.h). You want to call the function instead.


As for the segfault, you'd get one if the input file didn't exist or was unreadable, or if the output file was unwritable or couldn't be created.

Checking the return values of the fopen function would prevent this kind of error.

Otherwise, it works for me.
 
Code:
  s=(char*) malloc(10000); memset(s,0,10000);

check for return s here

s=(char *) malloc(10000);
if (!s)
errror
memset(s,0,10000);

as for casting, there are some compilers that make you provide the cast.
 
> there are some compilers that make you provide the cast.
Only those which pre-date ANSI-C are likely to complain, in which case, it's time to upgrade. ANSI-C has been around for 15 years now.

C++ compilers also complain, but the answer there is to either go all the way and start using new, or stick to malloc and use a C compiler.

As chipperMDW said, if you still get warnings from an uncast malloc, and you're sure you're compiling with ANSI-C, then you need to include stdlib.h

--
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top