[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: Segmentation fault




davidturetsky wrote:
> 
> I believe this is the code that was getting me into trouble, but it could be
> elsewhere
> 
>     fscanf (file, "%s", Title);

This one may get you into trouble if the Title array is not large enough
to hold the string.

>     fscanf (file, "%d %d %d %d %d %d", &m, &n, &it, &LT, &EQ, &GT);

This looks okay.

> 
> I was always uncomfortable with the notation esthetically, so I took
> advantage of the occasion to change all the i/o to stream style
> Once I got rid of "using namespace" it ran fine
> 
> Don't go away. I'll be back whining about some other problem!
> 
> Thanks, dancer. BTW, what's wrong with your code sample? I can see this is
> going to be daunting!


> > char * bitsofmemory = malloc (BIG_SIZE); FILE*f =fopen(FILENAME,
> ATTRIBUTE);
> > if (!(bitsofmemory && f)) {
> >    free(bitsofmemory); fclose(f) /* try to clean up and it dies...*/
> >    return ERROR;
> > }

This code tries to do both free the memory and close the file regardless
of which caused the error. A much neater and more readable version would
be:

char * bitsofmemory = malloc (BIGSIZE);
FILE * f = fopen(FILENAME, ATTRIBUTE);

if (bitsofmemory == NULL || f == NULL)
{
	if (bitsofmemory != NULL)
	{
		free(bitsofmemory);
	}
	if (f != NULL)
	{
		fclose(f);
	}
}

Matthew


Reply to: