Help ({char x[]; ...fgets(x,100,fp)...})

Wayne Throop throopw at dg_rtp.UUCP
Wed Nov 19 09:39:37 AEST 1986


> lubich at ethz.UUCP (Hannes Lubich)

>       char teststring[];
>       ...fgets(teststring, 100, myfptr)...
> [this gets "illegal instruction" when the procedure that contains this
>  returns, unless the fgets gets nothing from the f]

>       char *teststring;
>       ...fgets(teststring, 100, myfptr)...
> [this gets "bus error" at the fgets]

Um.  Well.  Let me put it this way.  You promised fgets that you would
allocate 100 bytes of storage for it to get things into from the f.
Remember that second argument?  The 100?  Well... you lied, you see.
That isn't nice.

In the first case, the compiler didn't complain about an illegal array
declaration, and allocated zero bytes for the array.  Then, the poor
fgets (confused by the pervarication of the second argument) clobbered
the return frame, causing the return to land in the middle of some
random memory location, where there was indeed (I suspect) an illegal
instruction.

In the second case, the compiler did just what was said perfectly.
Unfortunately what was said was that teststring is a pointer to an
undefined place (in particular, teststring was not initialized to point
to 100 characters).  Again, poor fgets relied on the promise implied by
its second argument, and in this case, when it tried to reference memory
that wasn't even there (through the uninitialized pointer that was the
first argument), the hardware slapped its "hand", yielding a bus error.

To fix the problem, keep your promise to fgets by allocating 100
bytes of storage, either by

        char teststring[100];
        ...fgets(teststring, 100, myfptr)...
or by
        char *teststring;
        teststring = (char *)malloc(100);
        ...fgets(teststring, 100, myfptr)...

Further, it is worth noting that lint will NOT normally catch the first
error. (I consider this a bug in lint, as well as a common pcc bug.  I
think Guy Harris has posted fixes for these, but I could be wrong).  On
the other hand, lint *WILL* probably catch the second error, saying:

        warning: teststring may be used before set


Lastly, I will note that this type of error is symptomatic of not
understanding the differences between arrays and pointers, and not
understanding allocation very well.  I suggest further study of the Holy
Scripture of K&R, and rigid fasting.  Scourging and wearing of hair
shirts is no longer in fashion (though it SHOULD be!).

(Chris Torek!!  You listenin'?  You might want to get out your
 zillion-line explanation of arrays and pointers.  I feel it may soon be
 needed.)

--
"The word 'language' is a misnomer -- languages are things like Dutch
 and English.  They are for telling jokes in and making love in."
                                --- Edsgar Dijkstra
--
"Mrs. Peel.... we're needed!"
-- 
Wayne Throop      <the-known-world>!mcnc!rti-sel!dg_rtp!throopw



More information about the Comp.lang.c mailing list