Bill Cunningham said:
I have put together this program that seems to do what I want without
error checking added yet. If I just run the program it produces a
segmentation fault. If I add the proper value say 43.56 it's fine. Does
anyone see what's wrong ? I have a c99 compiler. Thanks.
#include <stdio.h>
#include <stdlib.h>
int main ( int argc, char *argv[] ) {
FILE*fp;
double x;
x=strtod(argv[1],NULL);
If argc is 1 this passes a null pointer to strtod, which could well cause
a segfault.
Agreed.
I would recommend that the OP move the strtod() call to a point after the
argc test below...
At this point, argv[1] is guaranteed to be a non-null pointer. So, the op's
strtod() code should work properly here.
This fopen() opens the file for appending only. That means, "open or create
text ï¬le for writing at end-of-ï¬le"
You also need to check fp for nullness here.
Agreed.
Now, what is the above ftell() doing here? You (the OP) don't store the
results anywhere, and there are no usefull side-effects with ftell()
Hmmmm.... According to the standards,
"Opening a ï¬le with append mode ('a' as the ï¬rst character in the mode
argument) causes all subsequent writes to the ï¬le to be forced to the
then current end-of-ï¬le, regardless of intervening calls to the fseek
function."
and
"For a text stream, either offset shall be zero, or offset shall be a
value returned by an earlier successful call to the ftell function on a
stream associated with the same ï¬le and whence shall be SEEK_SET."
I'm afraid that this call won't reposition the "active position" in the file
for the next write (the fprintf() below). Not only does append mode negate
the fseek() call, but the whence value (SEEK_CUR) is not legal for the
(implied) file type (text, in the absence of a "b" mode character on the
fopen() call). Finally, /if/ this fseek worked, it wouold leave a
double-sized hole in the file (that being the movement implied by the
sizeof(double) against SEEK_CUR). Text files are rarely (never, in my
memory) sparse files; I'm not sure what that hole would do to subsequent
processing.
While I realize that, under C99, the 'falling off the edge' of the main()
function involves an implicit return of a value of 0 (which is the
equivalent termination status to EXIT_SUCCESS), it would be good to
a) check the results of the fclose(fp) call, and provide an explicit
EXIT_FAILURE if the file doesn't close properly, and
b) provide an explicit return of EXIT_SUCCESS otherwise
considering that you (the OP) have already used an explicit return of
EXIT_FAILURE in part of the logic above. Consistency is good.
--
Lew Pitcher
Master Codewright & JOAT-in-training | Registered Linux User #112576
http://pitcher.digitalfreehold.ca/ | GPG public key available by request
---------- Slackware - Because I know what I'm doing. ------