Jan 13, 2010 at 6:30pm UTC
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);
}
Jan 13, 2010 at 7:03pm UTC
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 Jan 13, 2010 at 7:05pm UTC
Jan 14, 2010 at 1:22am UTC
Thank you moorecm for your quick reply.
yes I am passing two arguments which are
/*lat=22.07;
lon=159.47;
*/
Jan 14, 2010 at 8:25pm UTC
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!!!
Jan 14, 2010 at 10:29pm UTC
Post the command-line and result that you are getting exactly as moorecm did.
Jan 16, 2010 at 1:20am UTC
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.
Jan 16, 2010 at 2:26am UTC
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 Jan 16, 2010 at 2:27am UTC