Segmentation fault

This is a discussion on Segmentation fault within the C Programming forums, part of the General Programming Boards category; Really sorry to post such a long code. But I have no idea where this segmentation fault is coming from. ...

  1. #1
    Registered User
    Join Date
    Nov 2009
    Posts
    59

    Segmentation fault

    Really sorry to post such a long code. But I have no idea where this segmentation fault is coming from.

    It prints fine until it calls splitme function and then i get a segementation fault.

    Code:
    int LineCount(FILE* fptr);
    double ReadFile(FILE *filename, int num_lines, double *array);
    double *splitme(double *array, size_t *p, size_t *q);
    	
    int main(void)
    {
    	size_t	j, encrypt_lines, bfun_lines, p1, q1;
    	size_t *p, *q;
    	FILE *encrypt, *blurring;
    	double *encrypt_array, *bfun_array, *split_array;
    	const char input1[]="toencrypt.txt", input2[]="bfun.txt";
    
    	encrypt=fopen("toencrypt.txt","r");	
    	blurring=fopen("bfun.txt","r");
    	
    	if (encrypt ==NULL || blurring == NULL)
        {
    	    printf("Cannot open required file!\n");
            printf("Please ensure your data file\n");
    	    printf("is in the correct directory\n");
    	    exit(EXIT_FAILURE);
    	}
    
    	encrypt_lines=LineCount(encrypt);
    	printf("%i\n", encrypt_lines); //remove
    	bfun_lines=LineCount(blurring);
    	printf("%i\n", bfun_lines); //remove
    	
    	encrypt_array = malloc ((encrypt_lines)*sizeof(double));
    	bfun_array = malloc ((bfun_lines)*sizeof(double));
    	split_array = malloc ((bfun_lines)*sizeof(double));
    	
    	*encrypt_array= ReadFile(encrypt, encrypt_lines, encrypt_array);
    	*bfun_array= ReadFile(blurring, bfun_lines, bfun_array);
    	
    	j=0; 
    	for(j=0; j<encrypt_lines; j++) 
    	{ 
    		printf("main encrypt array %i is %lf\n", j, encrypt_array[j]);
    	} 
    	
    	j=0; 
    	for(j=0; j<bfun_lines; j++)
    	{
    		printf("main bfun array %i is %lf\n", j, bfun_array[j]);
    	}
    	
    	fclose(encrypt);
    	fclose(blurring);
    	
    	*p = bfun_lines;
    	*q=0;
    	
    	*split_array= *splitme(bfun_array, p, q);
    	
    	j=0;
    	for (j=0; j<bfun_lines; j++)
    	{
    		printf("split main array %i is %lf\n", j, split_array[j]);
    	}
    	
    	printf("p is %i\n", p);
    	printf("q is %i\n", q);
    	
    	
    	
    	return(0);
    }
    
    int LineCount(FILE* fptr)
    {	
    	int count = 0;
    	char check[81];
    	char temp[81];
    	
    	while (fgets(temp, sizeof(temp), fptr) != NULL)
    	{
    		fscanf(fptr, "%s", &check);
    		if (check != "\n")
    		{
    			count++;
    		}
    	}
    	
    	count = ((count+1)*2);
    	return(count);
    }
    
    double ReadFile(FILE *filename, int num_lines, double *array)
    {
    	int	i;
    	
    	rewind(filename);
    	
    	i=0;
    	for(i=0; i<(num_lines); i++)
    	{
    		if((i & 1) == 0)
    		{
    			fscanf(filename, "%lf", &array[i]);
    		}
    		else
    		{
    			array[i]=0.0;
    		}	
    	}
    	
    	i=0;
    	for(i=0; i<(num_lines); i++)
    	{
    		printf("array %i is %lf\n", i, array[i]);
    	}
    	
    	
    	rewind(filename);
    	return(*array);
    	free(array);
    }
    
    double *splitme(double *array, size_t *p, size_t *q)
    {
    	size_t i, n, j;
    	double sum1, sum2; 
    	double *bfun_split, *ptr;
    	size_t array_size, centroid;
    	
    	array_size = *p;
    	
    	for (i=0; i<array_size; i++)
    	{
    		sum1 += (i * array[i]);
    		sum2 += array[i];
    	}
    	centroid = (round)(sum1/sum2);
    	printf("centroid is %d\n", centroid);
    	
    	*q = centroid - 1;
    	*p = array_size - centroid - 1;
    	printf("array size is %i\n", array_size);
    	printf("p is %i\n", p);
    	printf("q is %i\n", q);
    	bfun_split = malloc((array_size)*sizeof(double));
    	
    	i=0;
    	for (i=0; i<*p; i++)
    	{
    		bfun_split[i] = array[i+centroid];//allocate the right of the centroid
    	}
    	
    	i=0;
    	//x=(array_size - q - 1);
    	for (i=(array_size - *q - 1); i<array_size; i++)
    	{
    		bfun_split[i] = array[i-centroid]; //allocate the left of centroid
    	}
    	
    	i=0;
    	for (i=0; i<array_size; i++)
    	{
    		printf("split array %i is %lf\n", i, bfun_split[i]);
    	}
    	
    	free(array);
    	array = malloc((array_size)*sizeof(double));
    	
    	i=0;
    	for (i=0; i<array_size; i++)
    	{
    		array[i] = bfun_split[i];
    	}
    	
    	i=0;
    	for (i=0; i<array_size; i++)
    	{
    		printf("split array normal %i is %lf\n", i, array[i]);
    	}
    	
    	return(array);
    
    }

  2. #2
    a_capitalist_story
    Join Date
    Dec 2007
    Posts
    2,650
    Compile your code in debug mode and run it in the debugger. It will stop when and where the seg fault occurs.

  3. #3
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    21,660
    Quote Originally Posted by browser
    I have no idea where this segmentation fault is coming from.
    Set breakpoints at various places, then step through your code until you reach the segmentation fault. You then know that you can ignore the part of the code after that last breakpoint, for now.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  4. #4
    Registered User claudiu's Avatar
    Join Date
    Feb 2010
    Location
    London, United Kingdom
    Posts
    2,094
    Also, not sure if this is related but you are leaking memory in ReadFile:

    Code:
    	return(*array);
    	free(array);
    The free is dead code.
    1. Get rid of gets(). Never ever ever use it again. Replace it with fgets() and use that instead.
    2. Get rid of void main and replace it with int main(void) and return 0 at the end of the function.
    3. Get rid of conio.h and other antiquated DOS crap headers.
    4. Don't cast the return value of malloc, even if you always always always make sure that stdlib.h is included.

  5. #5
    Registered User
    Join Date
    Nov 2009
    Posts
    59
    Thanks...

    I used a printf statement to see where the segmentation fault occurred and found it was an uninitialised pointer...

    for some reason though...fixing it has led to a complete breakdown in the calculations in splitme!

    Code:
    i=0;
    	for (i=0; i<array_size; i++)
    	{
    		sum1 += (i * array[i]);
    		sum2 += array[i];
    	}
    is no longer working!!

  6. #6
    a_capitalist_story
    Join Date
    Dec 2007
    Posts
    2,650
    You're also using uninitialized variables sum1 and sum2 in that function
    Code:
    size_t i, n, j;
    	double sum1, sum2; 
    	double *bfun_split, *ptr;
    	size_t array_size, centroid;
    	
    	array_size = *p;
    	
    	for (i=0; i<array_size; i++)
    	{
    		sum1 += (i * array[i]);
    		sum2 += array[i];
    	}
    What's the value of sum1 the first time through that loop, before you add the value of (i * array[i]) to it?

  7. #7
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,799
    #1
    Code:
    int LineCount(FILE* fptr)
    {	
        int count = 0;
        char check[81];
        char temp[81];
    	
        while (fgets(temp, sizeof(temp), fptr) != NULL)
        {
            fscanf(fptr, "%s", &check);
            if (check != "\n")
            {
                count++;
            }
        }
    	
        count = ((count+1)*2);
        return(count);
    }
    The & in the fscanf call is wrong. The name of the array itself is sufficient since it represents an address.

    Also, you need to use strcmp to compare strings. Comparing check with "\n" is actually comparing the address of the two items in memory which are never going to be equal and thus the comparison will result in count always being incremented regardless of what is actually being stored in check.



    #2
    Code:
    encrypt_array = malloc ((encrypt_lines)*sizeof(double));
    bfun_array = malloc ((bfun_lines)*sizeof(double));
    split_array = malloc ((bfun_lines)*sizeof(double));
    	
    *encrypt_array= ReadFile(encrypt, encrypt_lines, encrypt_array);
    *bfun_array= ReadFile(blurring, bfun_lines, bfun_array);
    You aren't checking the malloc for successful results prior to using that memory. It makes little sense to be returning a value from your ReadFile function since the function itself takes care of loading data into the malloc'd memory. The way you're using the return value makes me question if you truly understand what is happening here.



    #3
    Code:
    	
    int main(void)
    {
        size_t j, encrypt_lines, bfun_lines, p1, q1;
        size_t *p, *q;
    
        ...
    	
        *p = bfun_lines;
        *q=0;
    Where is there ever memory being allocated for p/q?


    I've stopped at that. Haven't looked at all on your program's logic beyond this.
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

  8. #8
    Registered User
    Join Date
    Nov 2009
    Posts
    59
    Thanks very much for looking through it! I realise how tedious it must be.

    @hk;

    #1 : I am looking at the location for a \n and incrementing if it is stored. This way of doing it accounts for blank lines within my data file. It seems to be working for me in a variety of situations but I'm not sure if that is luck or not...

    #2 : I will be checking for NULL values in the final program...I am currently just trying to get things going...

    with return values do you mean the return from the external? What I believe I am doing is passing 2 specific files through a general file reader and returning the resultant array into 2 specific arrays...?

    #3 : I did post that this was in fact the problem that caused the segmentation fault and I have fixed this, thanks.

    @rags_to_riches;

    Yep, I had a look at that and I fixed it by setting sum1 and sum2 to zero before the loop!

    Thanks guys for your help, it is now running smoothly!

  9. #9
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    #2 : I will be checking for NULL values in the final program...I am currently just trying to get things going...
    This is the complete backwards way of doing it.


    Quzah.
    Hope is the first step on the road to disappointment.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Re: Segmentation fault
    By turkish_van in forum C Programming
    Replies: 8
    Last Post: 01-20-2007, 04:50 PM
  2. Segmentation fault
    By bennyandthejets in forum C++ Programming
    Replies: 7
    Last Post: 09-07-2005, 05:04 PM
  3. Segmentation fault
    By NoUse in forum C Programming
    Replies: 4
    Last Post: 03-26-2005, 02:29 PM
  4. Locating A Segmentation Fault
    By Stack Overflow in forum C Programming
    Replies: 12
    Last Post: 12-14-2004, 12:33 PM
  5. Segmentation fault...
    By alvifarooq in forum C++ Programming
    Replies: 14
    Last Post: 09-26-2004, 12:53 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21