PDA

View Full Version : segmentation fault


RoastP3nguin
2008-06-12, 05:03 PM CDT
Hi I've just started learning C using K&R, and for exercise 1-15 I have to rewrite a program, using my own function. I've written the program the function and the test for it, it compiles fine using gcc, but when I run it all I get is 'Segmentation fault'.
I've tried to figure this out, but don't really have a clue as I have just started, but here is the code I have written if this explains anything :P

/* convert to Fahrenheit from Celsius function */
#include <stdio.h>

/* cfconvert function */
float cfconvert(float celsius)
{
float fahr;

fahr = (celsius * 1.8) + 32.0;
return fahr;
}

/* test conversion function */
main()
{
float c, f;

printf("Enter 'float' temperature in Celsius to convert: ");
scanf("%f", c);

f = cfconvert(c);
printf("\nCelsius: %f.1\tFahrenheit: %f.1\n", c, f);
return 0;
}

Thanks for your help in advance. Roastie.

skoona
2008-06-12, 05:27 PM CDT
/* convert to Fahrenheit from Celsius function */
#include <stdio.h>

/* cfconvert function */
float cfconvert(float celsius)
{
float fahr = 0.0;

fahr = (celsius * 1.8) + 32.0;
return fahr;
}

/* test conversion function */
int main()
{
float c = 0.0, f = 0.0;

printf("Enter 'float' temperature in Celsius to convert: ");
scanf("%f", &c);

f = cfconvert(c);
printf("\nCelsius: %3.1f\tFahrenheit: %3.1f\n", c, f);
return 0;
}



1. scanf() wants the address of its binary variable. => &c
2. the printf() formatting '%f.1" printed like: "Celsius: 47.000000.1", I think you wanted '%3.1f' for "Celsius: 47.0"
3. consider using this compiler line to show all errors.
gcc -Wall -O2 -g -o program program.c -- straight C
gcc -Wall -O2 -g -lm -o program program.c -- include math.h library

RoastP3nguin
2008-06-13, 03:31 AM CDT
Hey, cheers, it all works now. Thanks for the help.

cable_txg
2008-06-16, 09:11 PM CDT
Just to add one more point to Skoona's:

use -ggdb to specifically include the gdb debugger, when errors occur run:

gddb <binary executable filename>
type: run <parameters for program if any>
at error point type: bt
The above should tell you which line number and what happened.

:D