[opensuse] c - Segmentation fault on 11.4 - need help figuring out (strtod?)



Guys,

Helping my son with a simple little area program, I am running into a segmentation fault after program execution. It seems to be with the strtod conversion, but I can't figure out why. It compiles without issue and executes fine, but then I get a Segmentation Fault error after the program ends. The code is:

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

int main (int argc, char *argv[]) {

if (argc < 2) {
fprintf(stderr, "\nERROR: Usage: %s radius list\n", argv[0]);
fprintf(stderr, "\n example: %s 4 16 21 8 for area calculations\n\n", argv[0]);
exit (1);
}

char *p;
int i;
double rad;
double area;

for (i=1;i<=argc;i++) {
rad = strtod(argv[i],&p);
area = M_PI*rad*rad;
printf(" rad : %5.2f area : %10.4f\n", rad, area);
}

return 0;
}

It compiles without error on 11.4 (x86_64) with:

gcc -Wall ztst.c -o ztst

It seems to run fine:

13:22 alchemy:~/dev/prg/ccpp/src-c/misc> ./ztst 1 2 3 4
rad : 1.00 area : 3.1416
rad : 2.00 area : 12.5664
rad : 3.00 area : 28.2743
rad : 4.00 area : 50.2655
Segmentation fault

So where is this segfault coming from? I have experimented and commented out of the strtod function and just hard coded values for rad (i.e.: rad = (double) i;) and it runs without a segfault. Am I doing something wrong with the strtod call? What say the experts?

--
David C. Rankin, J.D.,P.E.
--
To unsubscribe, e-mail: opensuse+unsubscribe@xxxxxxxxxxxx
To contact the owner, e-mail: opensuse+owner@xxxxxxxxxxxx



Relevant Pages

  • Re: [opensuse] c - Segmentation fault on 11.4 - need help figuring out (strtod?)
    ... Helping my son with a simple little area program, I am running into a segmentation fault after program execution. ...
    (SuSE)
  • Re: seg fault
    ... segmentation fault. ... This test should come before the conversion with strtod. ... Well I've added error checking to ftell, fseek, and fopen and the ... For ftell and fseek -1. ...
    (comp.lang.c)
  • Re: problem with atof
    ... Program received signal SIGSEGV, Segmentation fault. ... using strtod() correctly is more complicated than using atof. ... problem with pointers, but a call to strtod(nptr, endptr) gives strtod ...
    (comp.lang.c)
  • Re: seg fault
    ... segmentation fault. ... This test should come before the conversion with strtod. ... What is the purpose of calling ftell and discarding the return? ... When you open a file in the append mode the file position indicator is ...
    (comp.lang.c)
  • Re: seg fault
    ... segmentation fault. ... If I add the proper value say 43.56 it's fine. ... This test should come before the conversion with strtod. ... When you open a file in the append mode the file position indicator is ...
    (comp.lang.c)