Re: [HACKERS] What is nameout() for?
От | Tom Lane |
---|---|
Тема | Re: [HACKERS] What is nameout() for? |
Дата | |
Msg-id | 13441.942290008@sss.pgh.pa.us обсуждение исходный текст |
Ответ на | Re: [HACKERS] What is nameout() for? (Mike Mascari <mascarim@yahoo.com>) |
Список | pgsql-hackers |
Mike Mascari <mascarim@yahoo.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
В списке pgsql-hackers по дате отправления: