Re: [HACKERS] What is nameout() for?

From: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
To: Mike Mascari <mascarim(at)yahoo(dot)com>
Cc: Bruce Momjian <maillist(at)candle(dot)pha(dot)pa(dot)us>, pgsql-hackers(at)postgreSQL(dot)org
Subject: Re: [HACKERS] What is nameout() for?
Date: 1999-11-11 03:13:28
Message-ID: 13441.942290008@sss.pgh.pa.us
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-hackers

Mike Mascari <mascarim(at)yahoo(dot)com> writes:
> Actually, I have 'C' question regarding the above code. Where does the
> "-" live in RAM? Does the compiler generated a data hunk such that this
> string will be apart of the final executable and each invocation of this
> routine would result in a pointer to that 'global' location being
> returned?
> Or does it allocate the memory for, and initialize, the "-" on the stack?
> If so, isn't returning a "-" a dangerous act?

As Bruce already explained, the existing code returns a pointer to a
constant string "-" sitting somewhere in the program's text segment
(or data segment, possibly, depending on your compiler). So it's OK
in the sense that the pointer still points at well-defined memory
even after the function returns. But I believe the code is bogus
anyway, because one path returns palloc'd storage and the other
doesn't. If the caller pfree'd the returned pointer, it'd work
just until nameout was given a NULL pointer; then it'd coredump.

> In fact, isn't returning a "-" dangerous either way without the
> protoype being:

> const char *nameout(NameData *s);
> ^^^^^

That's a different issue: if the caller tries to *modify* the returned
string, should the compiler complain? If the caller tries that, and
the compiler doesn't complain, and the compiler puts the constant string
"-" into data segment, then you've got trouble: that supposedly constant
string will get changed and will no longer look like "-" on its next
use. (Shades of Fortran II :-(.) But I'm not very worried about that
in practice, because most of the developers use gcc which puts constant
string in text segment. Any attempt to modify a constant string will
instantly coredump under gcc, so the logic error will be found and fixed
before long.

The trouble with declaring nameout and similar functions to return
const char * is that C (and C++) don't distinguish "thou shalt not
modify" from "thou shalt not free". Ideally we'd like to declare
nameout as returning a string that the caller can't modify, but can
free when no longer needed. We can't do that unfortunately...

regards, tom lane

Browse pgsql-hackers by date

  From Date Subject
Next Message Tom Lane 1999-11-11 04:29:56 Re: [HACKERS] Arrays broken on temp tables
Previous Message Tom Lane 1999-11-11 02:56:42 Re: [HACKERS] IN clause and INTERSECT not behaving as expected