Segmentation error... malloc. Please help

This is a discussion on Segmentation error... malloc. Please help within the C Programming forums, part of the General Programming Boards category; Hello, i am writing a program to compute an integral... the values of x and f(x) are given in a ...

  1. #1
    Registered User
    Join Date
    Oct 2010
    Posts
    13

    Exclamation Segmentation error... malloc. Please help

    Hello, i am writing a program to compute an integral... the values of x and f(x) are given in a file (2 columns, 10000 rows), i read from the file and then use the summation method to compute the integral. Command line arguments are used to get the upper limit

    The program must allocate memory (i've used malloc), and use an external function to compute the intergral. The program compiles, but i get a segmentation error. I THINK THE PROBLEM IS IN THE EXTERNAL FUNCTION, because i blocked off the rest of the code with comments, and the segmentation error disappeared.

    Please you could you describe in as much detail as you can where I am going wrong, as I am not very competent in C.

    Thanks!!!


    Code:
    /****************************************************
    ** Module: C for Scientists 2010
    ** Student ID: 0915539
    ** PHUJEB
    ** Assignment 3
    ****************************************************/
    
    #include <stdio.h>
    #include <stdlib.h>
    #include <math.h>
    
    double integration(double, int);
    
    int main(int argc, char* argv[])
    
    {
       FILE          *input;
       int           ac=0, col, i, j, rec, ns;  
       float         a, b;
       const char    inp_fn[]="px270prog3a.dat";
       char          buf[1025];
       char          *ch, *tokptr, *strptr=buf;
       double        *x, *fx, tmp, result;
    
    	input = fopen(inp_fn, "r");
    	
    	if( argc != 2 ) /*Checking for the correct number of arguments, and showing user how to use correct format*/
        {  printf("The upper limit was not entered correctly. Usage: %s UpperLimit\n", argv[0]);
           exit(EXIT_FAILURE);
        }
    	
        if(input == (FILE*) NULL)
        {
            printf("**** Error opening input file  ****\n");
    		exit(EXIT_FAILURE);
        }
    	
    	else
    	{
    		b=atoi(argv[1]);
    		
    		for (i = 0; i < 9999; i++)
    		{
    		fscanf(input, "%f %f", &x[i], &fx[i]); /*just added this bit to read the file, some later code may be unneccesary*/ 
    		}
    	
    		fgets(buf, 1024, input); 
    	
    		while((tokptr=(char*)strtok(strptr, " \t\n\r\b,")) != NULL)
    		{   
    	
    		while(fscanf(input,"%lf",&tmp) == 1) ns++;
    		
    		ns = ns / ac;
    		
    		/* Now we know how big of an array to allocate */
    		
    		x = (double*) malloc((ns+1)*sizeof(double));
    		fx = (double*) malloc((ns+1)*sizeof(double));
    		printf("Allocated memory for %d records\n",ns+1);
    
    		/* We have already read the file, so we will rewind
    		   it to start from the top again */
    		rewind(input);
    		i=0; rec = 0;
    		while(fscanf(input,"%lf",&tmp) == 1)
    		{
    		  j = (rec % ac) + 1;
    		  if(j==1)
    				 x[i] = (double)(tmp);
    		  else if(j==2)
    			  {
    				  fx[i] = (double)(tmp);
    				   i++;
    			  }
    			  rec++;
    		}
    		
    		}
    	
    		for(i=0; i<b; i++)
    		{
    		result = integration(fx, rec-1);
    		}
    		printf("The result of the integral is: %lf\n", &result);
    		
    		fclose(input);
    	
    	}
    	
    }
    
    double integration(double data, int n)
    {
       int i;
       double area, x[i], fx[i];
       
       area = fx[i-1] * x[i] - x[i-1];
       
       return(area);
    }
    Last edited by Rollo; 12-05-2010 at 01:34 PM.

  2. #2
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,548
    10 posts, no code tags - what does this mean?

    Answers next week.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  3. #3
    Registered User
    Join Date
    Oct 2010
    Posts
    13
    Quote Originally Posted by Salem View Post
    10 posts, no code tags - what does this mean?

    Answers next week.
    sorry, completely forgot about the tags. edited them in now

  4. #4
    a_capitalist_story
    Join Date
    Dec 2007
    Posts
    2,650
    Code:
    double integration(double data, int n)
    {
       int i;
       double area, x[i], fx[i];
       
       area = fx[i-1] * x[i] - x[i-1];
       
       return(area);
    }
    Welcome to the world of functions that do absolutely nothing of use. You pass in two arguments, completely ignore them, create arrays with uninititalized variables, do operations on said arrays which contain who knows what, and return the result. Were you really expecting this to work?

    Code:
    printf("The result of the integral is: %lf\n", &result);
    Then you print the address of the return value.

  5. #5
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    About this....

    After reading the file and counting elements...
    Code:
    ns = ns / ac;
    1) Why are you dividing your count?
    2) What is the value of ac at that point?

    Looks to me like you're going to get a divide by 0 error.

  6. #6
    Registered User
    Join Date
    Oct 2010
    Posts
    13
    Thanks to some... I do appreciate the help, but theres no need to be so rude, how will i learn from being shouted at.

  7. #7
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Quote Originally Posted by Rollo View Post
    Thanks to some... I do appreciate the help, but theres no need to be so rude, how will i learn from being shouted at.
    I saw no unusual rudeness here.

    It is an evolved culture amongst programmers (and other high tech people) that they speak very directly and honestly. It has it's advantages... you ask a question, you get the unvarnished truth... Would you settle for anything less?

  8. #8
    Registered User
    Join Date
    Dec 2010
    Posts
    1
    did your program work in the end or did you need more help?

  9. #9
    Registered User
    Join Date
    Oct 2010
    Posts
    13
    No, i managed to get the program to work in the end: i changed it significantly though, looking back though i can see why you ripped it apart, it was pretty terrible:

    Here is the "finished" code, you could look through it to check for anything that could be improved if you wish, it would be helpful.


    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <math.h>
    
    float *x, *fx, a = 0, *int_ptr;
    
    float integration(float x[], float fx[], float a, float b, float *int_ptr);
    
    int main(int argc, char* argv[])
    {
       FILE          *input;
       int           i, z, no_rows;  
       const char    inp_fn[]="px270prog3A.dat";
       float         result, b;
    
       input = fopen(inp_fn, "r");
    
       if( argc != 2 ) /*Checking for the correct number of arguments, and showing user how to use correct format*/
       {
       printf("The upper limit was not entered correctly. Usage: %s UpperLimit\n", argv[0]);
       exit(EXIT_FAILURE);
       }
    
       if(input == NULL) /*Checks the input was opened*/
       {
       printf("**** Error opening input file  ****\n");
       exit(EXIT_FAILURE);
       }
    
       else
       {
    
         while((z = fgetc(input)) != EOF) /*counting the number of rows in the input file*/
         {
         if( z == '\n')
         no_rows++;
         }
    
         rewind(input);
    
         x = (float*) malloc((no_rows)*sizeof(float)); /*allocates memory*/
         fx = (float*) malloc((no_rows)*sizeof(float));
    
         sscanf(argv[1], "%f", &b); /*Reading the upper limit, b, from the command line*/
    
         if( b < 0 || b > (M_PI_2)) /*Checks the upper limit is in the range of x in the file*/
         {
         printf("The upper limit was not in the range of the function: 0 - %f\n", M_PI_2);
         exit(EXIT_FAILURE);
         }
    
         for (i = 0; i < no_rows; i++)
         {
         fscanf(input, "%f %f", &x[i], &fx[i]); /*Reads the file, assigns first column to x, second to fx*/
         }
    
    	 rewind(input);
    	
         int_ptr = &result;
    	 integration(x, fx, a, b, int_ptr);
    
         printf("Integral between %f and %f is %f\n", a, b, result);
         fclose(input);
    
       }
    }
    
    float integration(float x[], float fx[], float a, float b, float *int_ptr) /*External function that computes the summation*/
    {
       int i = 1; /*initialising variables*/
       *int_ptr = 0;
    
       while(x[i] >= a && x[i] <= b )
       {
       *int_ptr += fx[i-1] * (x[i] - x[i-1]); /*summation*/
       i++;
       }
       
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Segmentation fault
    By bennyandthejets in forum C++ Programming
    Replies: 7
    Last Post: 09-07-2005, 05:04 PM
  2. Segmentation fault
    By Buckshot in forum C++ Programming
    Replies: 14
    Last Post: 06-23-2005, 08:20 AM
  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