On Thu, 3 Feb 2005, Jos Houtman wrote:
>> But you shouldn't free(tmp) after putenv():ing SHELL, since that will
>> free the memory that is actually used in the environment, allowing
>> someone else to write there later on, possibly introducing another
>> security hole. (Getting repetitive, yes, I know.)
>that seems the hardest part to learn, when to free memory and when not.
>are there any basic rules/guidelines for that?.

Hi, Jos.

The man pages, and the open specifications that you can find online, give
you what you in general need to know. But old man pages were very poor,
and even for a guy who's done C and C++ programming for 15 years, I still
run into problems now and then. I've gotten used to checking with POSIX
and the Single Unix Specification when I'm in doubt. And as a rule of
thumb, you should always check the man pages.

The last pit I fell into was with this IMAP server, and openlog(). The man 
pages said:

       void openlog(const char *ident, int option, int facility);
       (...)

       openlog()  opens  a  connection to the system logger for a
       program.  The string pointed to by ident is  prepended  to
       every  message,  and is typically set to the program name.

Notice how it says "the string pointed to by...". This means that you
can't use a temporary string such as the C++ myString.c_str(); it has to
be a compile-time initialized constant string, or one that lives for as
long as syslog is used. putenv()  needs an allocated string, which really
sucks because all memory profilers will report it as a potential memory
leak. A way around putenv's problem is to use static char* data, but of
course this won't be reentrant. stdlib calls sometimes suck ;-).

>> A side note, the construct (*user).pw_name can (should) be written as
>> user->pw_name, which is a lot easier at least on my eyes. :)
>I hadn't passed that chapter in the book yet, next chapter now is "Input
>and Output". In my opinion the most annoying part of programming.

You should try Qt ;-)... /me hides

>> > Are you sure the function generates the segmentation fault?
>At the time i was because it only happend for the user that was not
>in /etc/passwd. But it turned out to be an improper call to free()
>> Your code looks good, but I may be overlooking something.
>Thanks, c turned out be quite easy to learn, atleast the grammer.
>this should be the latest update

And fyi, a fine way of checking your programs for buffer overflows and
memory leaks is to run them through valgrind: http://valgrind.kde.org/. It
will show you what went wrong, where and why.

Andy :-)

--
Andreas Aardal Hanssen   | http://www.andreas.hanssen.name/gpg
Author of Binc IMAP      |  "It is better not to do something
http://www.bincimap.org/ |        than to do it poorly."

Reply via email to