delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1996/05/31/22:31:46

From: idr AT cs DOT pdx DOT edu (Ian D Romanick)
Message-Id: <199606010225.TAA08311@sirius.cs.pdx.edu>
Subject: Re: printf("%s",0) - Segmentation fault
To: vessers AT mpce DOT mq DOT edu DOT au (Victor R. Essers)
Date: Fri, 31 May 1996 19:25:35 -0700 (PDT)
Cc: morellov AT mbox DOT vol DOT it, djgpp AT delorie DOT com
In-Reply-To: <01BB4FB0.9776BC00@vessers.mpce.mq.edu.au> from "Victor R. Essers" at Jun 1, 96 11:50:54 am
MIME-Version: 1.0

> > The following line will produce a "Segmentation fault" -error on some platforms/compilers:
> > printf("%s",0);
> > 
> > However, some platforms/compilers will produce a string like "(Null)" or similar.
> > 
> > Is it possible to tell the compiler what to do in this situation?
> 
> You cannot expect a compiler to act as an interpreter!
> The C compiler simply puts in the stack the pointer to
> the constant string "%s" and the integer value and then
> calls a function. (Note that 0 could be a 16 bit value
> in some environment!). The compiler knows nothing about
> the use of such parameters in the called function.

However, the printf() function could know what to do in this situation. 
I also have seen this behavior.

> When you get the output (null) from the printf function,
> it means your program has a BUG. If you need to treat
> a NULL string pointer as an empty string, you could
> substitute the pointer pp with the expression:
> (pp == NULL ? "" : pp)

This is by far a more secure solution.  Relying on the little things
that a given compiler does *will* cause you trouble on any other
compiler.

-- 
"Every generation tries to extend the limits of | Visit the EPN coder page at:
 what is possible.  The trouble now is that     |
 ANYTHING is possible."  -- Yoyo Ma             |  http://www.cs.pdx.edu/~idr

- Raw text -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019