1
#include <stdio.h>
#include <math.h>


struct coeff
{
    int a;
    int b;
    int c;
};


struct roots
{
    double r1;
    double r2;
};


void calculateRoots(struct coeff*, struct roots*);


int main(int argc, char const *argv[])
{
    struct coeff *c;
    struct roots *r;
    c = NULL;
    r = NULL;

    c->a = 10;
    c->b = 20;
    c->c = 30;

    calculateRoots(c,r);

    printf("The roots are : %lf & %lf\n", r->r1, r->r2);

    return 0;
}


void calculateRoots(struct coeff *cef, struct roots *rts)
{
    rts->r1 = (-(cef->b) + sqrt((cef->b)*(cef->b) - 4*(cef->a)*(cef->c)) ) / 2*(cef->a);
    rts->r2 = (-(cef->b) - sqrt((cef->b)*(cef->b) - 4*(cef->a)*(cef->c)) ) / 2*(cef->a);
}`

Code compiles but on running gives a Segmentation Fault (core dumped) error

Whats wrong in this code ?? I'm using a gcc compiler version : gcc (Ubuntu/Linaro 4.7.3-1ubuntu1) 4.7.3

Please help, I'm waiting live

amarVashishth
  • 847
  • 3
  • 12
  • 26
  • You might get some insight from this old answer of mine. It's C++ not C, but the same principle holds. http://stackoverflow.com/a/334752/5987 – Mark Ransom Jun 07 '13 at 18:03

2 Answers2

5

You need to allocate memory for both coeff and roots structures. Replace the two lines

c = NULL;
r = NULL;

by

c = malloc ( sizeof ( struct coeff ) );
r = malloc ( sizeof ( struct roots ) );

Also, at the end of code (before the return statement), deallocate the memory by

free ( c );
free ( r );
unxnut
  • 8,509
  • 3
  • 27
  • 41
0
   struct coeff *c;
    struct roots *r;

These are pointers - they are not the structs themselves - they are "aimed" nowhere. Ditto for roots

jim mcnamara
  • 16,005
  • 2
  • 34
  • 51