Path: csiph.com!eternal-september.org!feeder.eternal-september.org!mx02.eternal-september.org!.POSTED!not-for-mail From: Keith Thompson Newsgroups: comp.lang.c Subject: Re: A printf question. Date: Tue, 13 Oct 2015 10:45:36 -0700 Organization: None to speak of Lines: 38 Message-ID: References: Mime-Version: 1.0 Content-Type: text/plain; charset=us-ascii Injection-Info: mx02.eternal-september.org; posting-host="945944de09706c9b4e29b53c9d2efdc2"; logging-data="5826"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX18NiAnekO7s2WpDnpaAGLjm" User-Agent: Gnus/5.13 (Gnus v5.13) Emacs/23.1 (gnu/linux) Cancel-Lock: sha1:rGXglWsivnjerVKcqv3gloOUrfg= sha1:t2J4i1nOY1aZ6EYuaPRIHUu8T7s= Xref: csiph.com comp.lang.c:72727 Malcolm McLean writes: > On Tuesday, October 13, 2015 at 3:12:07 PM UTC+1, Mehdi Amini Valashani son of Bahram wrote: >> // Following a discussion on a forum, I got this code snippet: >> >> #include >> #include >> >> int main(void) >> { >> const char * const message="My str\n"; >> >> //printf("%s", message); // This seems to be correct. >> printf(message); // Should not this produce a diagnostic? >> >> return EXIT_SUCCESS; >> } >> > No, its normally a bad idea to pass a string composed on the fly as > the format argument to printf (largely because you might have embedded > percent signs in it), but it's not prohibited, and occasionally it's > the right thing to do. printf("%s", message) is the normal way of > printing out a string whose contents aren't known at the point of > making the call, however. Either that or fputs(message, stdout), or puts(message) if you want to add a newline. printf format strings are typically literals, which are safe *if* the code is written carefully and correctly. A format string can be generated at run time by some other means, but you *must* be careful not to include '%' characters that you didn't intend to. Using unchecked user input as a format string is arbitrarily dangerous. -- Keith Thompson (The_Other_Keith) kst-u@mib.org Working, but not speaking, for JetHead Development, Inc. "We must do something. This is something. Therefore, we must do this." -- Antony Jay and Jonathan Lynn, "Yes Minister"