[OCLUG-devel] Trouble with strings and files
James Colannino
james at colannino.org
Tue Jul 6 21:19:35 PDT 2004
Tim Thelin wrote:
> James Colannino wrote:
>
>> Hey everyone. One of the programming excercises in my C book asked me
>> to write a program that will take numbers from a file, place all the
>> numbers divisible by 3 in one file, and all the numbers not divisible
>> by 3 in another file. I wrote a program that compiles without any
>> fatal errors (albeit I do get some warnings; I will post if asked),
>> but when I run the program with the correct number of arguments, it
>> seg faults. I ran strace on it to see what it was failing on, but had
>> trouble locating the exact problem. Below are URLs pointing to both
>> the C source and strace's output:
>>
>> http://james.colannino.org/mailinglist/strace.output
>> http://james.colannino.org/mailinglist/twolist.c
>>
>> I'm sure there's some blatantly obvious and stupid thing that I'm
>> doing, but for the life of me, I can't figure out what it is. I'm
>> hoping that someone more experienced can hit me over the head with the
>> correct answer :) Thanks very much in advance.
>>
>> James
>
>
> You probably only want to use strace for debugging when your trying to
> figure out what system calls are being used and with what arguments.
> Otherwise its not too useful as a general debugging tool. Getting
> familiar with gdb (or one of its graphical front ends) would probably be
> more useful to you.
>
> I believe the issue is your sscanfs for turning the number into a
> string. You should actually be using sprintf there, not sscanf. scanf
> is for turning a string something and parsing it into smaller units
> (scaning); printf is used for taking smaller units and turning them into
> a single string. So you want to take your smaller unit (the number) and
> turn it into the string you want to place in the file with your fputs.
>
> Its probably segfaulting because scanf needs a string as a first arg and
> your passing in a number; remember how strings are just char pointers...
> and numbers can be cast as a char* quite easily... so scanf is using
> your number as a memory address and seg faulting. One of the compiler's
> warnings probably hinted at this (as a personal rule I always compile
> with -Wall (all warnings) and make sure i've solved every warning before
> continuingor at least made sure i know why i'm ignoring a warning).
>
> Btw you could combine your (soon to be) sprintfs and fputs into a single
> fprintf, and you could combine your fgets and scanf into a single fscanf.
Extremely helpful. Thank you :)
James
--
My blog: http://www.crazydrclaw.com/
My homepage: http://james.colannino.org/
"There are no uninteresting things; only uninterested people." --G.K.
Chesterton
More information about the OCLUG-devel
mailing list