Segmentation fault

Hi everybody, I am new on using both Linux and C++. I have got a small program (I didn't wrote it)which main aim is to convert geographic coordinates to a specific coordinates system. The code is compiled using gcc but when I try to run it I got a message error "Segmentation fault". I was looking in the Internet and it seems that there are many sources for this error but I don't know which one causes my problem. Your help is highly appreciated.

here is the code

#include<stdio.h>

#include<stdlib.h>

#include<math.h>

main(int argc, char *argv[])

{

double degrad = 0.017453293;

double earthrad = 6371.2;

double stdlat = 60.;

double stdlon = 105.;

double mesh_len = 4.7625;

double tlat, re, latrad, lonrad, r, x, y;

double hrapx,hrapy;

double lat,lon;

lat=atof(argv[1]);

lon=atof(argv[2]);

/*lat=22.07;

lon=159.47;

*/

tlat = stdlat*degrad;

re = (earthrad*(1. + sin(tlat)))/mesh_len;

latrad = lat * degrad;

lonrad = (lon + 180. - stdlon) * degrad;

r = re * cos(latrad) / (1. + sin(latrad));

x = r * sin(lonrad);

y = r * cos(lonrad);

/*printf("x = %f y=%f r=%f\n",x,y,r);*/

hrapx = x + 401;

hrapy = y + 1601;

printf("%f %f hrapx = %3f hrapy = %3f \n",lat,lon,hrapx,hrapy);

}

Are you passing two arguments to it on the command line? It appears to be expecting two floating point numbers.

These lines are accessing the argv array without previously checking if argc > 2.
1
2
3
lat=atof(argv[1]);

lon=atof(argv[2]);
Last edited on
Thank you moorecm for your quick reply.

yes I am passing two arguments which are
/*lat=22.07;

lon=159.47;
*/
It worked fine for me:
$ ./test 22.07 159.47
22.070000 159.470000 hrapx = -967.493106 hrapy = 623.782075 
yes the results that you have got are correct, but I don't know why it is not working in my station. I am having the same error message!!!
Post the command-line and result that you are getting exactly as moorecm did.
Thank you guys it is working now

$ ./convert 22.07 159.47
22.070000 159.470000 hrapx = -967.493106 hrapy = 623.782075

As I said I am new in programming and I was putting the input values inside the code before compile it and the I run the code without giving it the inputs. I guess this caused the error message.
Yes, that is because you left this in your code:

1
2
3
lat=atof(argv[1]);

lon=atof(argv[2]);


You need to check that argc > 2 before doing that.

1
2
3
4
5
6
7
8
if (argc > 2) {
    lat = atof(argv[1]);
    lon = atof(argv[2]);
} else {
    cout << "Using default values for latitude and longitude." << endl;
    lat=22.07;
    lon=159.47;
}


edit: fixed argv/argc screw-up.
Last edited on
Topic archived. No new replies allowed.