Hacker News new | ask | show | jobs
by unwind 4224 days ago
The article spoke about a suspected memory leak in setenv(), I assume it uses uClibc but it was a bit light on the details (no source code links in the article, that I could find).

I dug up this link: http://git.uclibc.org/uClibc/tree/libc/stdlib/setenv.c?id=30... which I believe is the relevant function.

Unsurprisingly for this level of library code, it's not 100% super-obvious or easy to understand. Especially the details on the in-library memory management are unknown to me, but I thought it might be interesting.

2 comments

The whole putenv()/setenv()/unsetenv()/environ API is inconsistent hack that is essentially impossible to implement without introducing memory leak in at least one of these operations without introducing some complex additional book keeping. The good news is that there aren't that many reasons to actually use these functions, as only reasonable usecase for modifying environment is changing environment of spawned subprocesses, which can be done by constructing your own environ and passing it as envp argument to exec().

On the other hand the memory leak is mostly negligible and one would assume that for reasonable program that calls setenv (ie. does not call setenv in a loop) probably smaller than cost of the aforementioned extra book keeping.

I used the older uC-libc, not the newer uClibc (no dash in the name). You're right. There's a tiny leak in this version of setenv(), when you set a value for an environment var that already exists. It leaks the old value, which seems to be an intentional design choice, in case anything was holding on to a pointer to it.
> Unsurprisingly for this level of library code, it's not 100% super-obvious or easy to understand.

Sounds like you visit the wrong libraries. Try plan9's