Kenneth Brody <> writes:
> On 12/5/2010 1:25 AM, Zach wrote:
> [...]
>> fprintf(fpin,"<!DOCTYPE html PUBLIC "-"//W3C//DTD XHTML 1.1//EN\n");
>> fprintf(fpin,"
>> http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd>\n");
> [...]
>
> I see others have already answered, but you may be wondering why the code
> you wrote didn't work, yet compiled.
>
> Consider your "string":
>
> "<!DOCTYPE html PUBLIC "-"//W3C//DTD XHTML 1.1//EN\n"
>
> This is how C sees it:
>
> A string literal: "<!DOCTYPE html PUBLIC "
> A minus sign: -
> Another string literal: "//W3C//DTD XHTML 1.1//EN\n"
>
> So, your "string" is actually an integer representing the difference between
> two "char*" values. (On my system, it's -24, though it could be virtually
> anything.)
In fact, the behavior of the subtraction is undefined, since it
attempts to subtract pointers to two distinct objects. As always,
one possible result of undefined behavior is to quietly yield some
result which may or may not make sense.
> Now, on my system, running your first fprintf line crashes the program, as
> fprintf() is expecting a char*, not an integer, as the second parameter. (I
> also get a warning about this at compile time.)
Again, passing a value of type ptrdiff_t (the signed integer type of the
result of subtracting two pointer values) to fprintf() with a format
that expects a char* argument results in undefined behavior. In this
particular case, the likely result is that the value -24 (if that's what
you happen to get) is interpreted as a char* value, possibly as
(char*)0xffffffe8 on a 32-bit system. Since there probably isn't
anything accessible at that address, a program crash is a very likely
result.
--
Keith Thompson (The_Other_Keith)
kst- <http://www.ghoti.net/~kst>
Nokia
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"