LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   GCC Compiling (Linux), "Segmentation Fault" (https://www.linuxquestions.org/questions/programming-9/gcc-compiling-linux-segmentation-fault-277060/)

Kenji Miyamoto 01-12-2005 05:14 PM

GCC Compiling (Linux), "Segmentation Fault"
 
I'm trying to write a program to solve the quadratic exuation and find the vertex. I managed to get it to compile in both the GCC and the G++ (It's written in C), but I can't get it to actually run. Right after entering the first number, it gets a segmentation fault.
Konsole:
Code:

[neil@localhost ~]$ gcc '/home/neil/Desktop/calc.c' -o '/home/neil/Desktop/calc.exe' -lm
[neil@localhost ~]$ '/home/neil/Desktop/calc.exe'
Welcome to my quadratic program,
 the Quradratic Calculator;
The format is =_x^2 + _x + _
=2
Segmentation fault

Source:
Code:

#include <stdio.h>
#include <math.h>
float quad1(int x1, int x2, int x3);
float quad2(int x1, int x2, int x3);
float med(float y1, float y2);
float val(float z1, float z2, float z3, float mid);


int main()
{
        int ax, bx, cx;
        float y1, y2, mid, mival;
        printf("Welcome to my quadratic program,\n the Quradratic Calculator;\nThe format is =_x^2 + _x + _\n=");
        scanf("%d", ax);
        printf("x^2 +");
        scanf("%d", bx);
        printf("x + ");
        scanf("%d", cx);
        y1 = quad1(ax, bx, cx);
        y2 = quad1(ax, bx, cx);
        mid = med(y1, y2);
        mival = val(ax, bx, cx, mid);
        printf("The 0s are (%f, 0) and (%f, 0)\nThe vertex is (%f, %f).\n", y1, y2, mid, mival);
        return 0;
}

float quad1(int x1, int x2, int x3)
{
        float y;
        y = (-x2 + sqrt( pow(x2, 2) - 4 * (x1 * x3)))/(2 * x1);
        return y;
}

float quad2(int x1, int x2, int x3)
{
        float y;
        y = (-x2 - sqrt( pow(x2, 2) - 4 * (x1 * x3)))/(2 * x1);
        return y;
}

float med(float y1, float y2)
{
        float median;
        median = (y1+ y2)/2;
        return median;
}

float val(float z1, float z2, float z3, float mid)
{
        float mima;
        mima = (z1 * pow(mid, 2)) + (z2 * mid) + z3;
        return mima;
}

Segmentation faults have caused delays with my programming before. What do they mean? How can I fix this one?

itsme86 01-12-2005 06:08 PM

A segmentation fault means "Invalid memory reference". Your program is given a certain range of memory to play with, and if you attempt to access memory outside of that range the kernel will stop it before it does damage.

To fix it, you should find your programming error =)

EDIT: Looking at the code, I found the problem within 5 seconds. scanf() needs the address of where to store the data. You should be using like &ax instead of ax.

vose 01-13-2005 01:44 AM

You really want to become familiar with gdb and ddd;
they can help you locate such problems (usually).


All times are GMT -5. The time now is 05:18 AM.