bitwiseworks / libc

LIBC Next (kLIBC fork)
9 stars 4 forks source link

Make setenv not leak memory #103

Open dmik opened 3 years ago

dmik commented 3 years ago

According to POSIX specs, putenv is inevitably subject to leaks because it must add the passed string to environ w/o making a copy. This way, it's never known when it's safe to free it even if it's known it was allocated on the heap. So, this is "by design" and will be like that forever until the standard changes which is unlikely — the standard deprecates putenv by recommending to use setenv instead.

However, setenv is allowed to make copies of its arguments so such memory may be properly released when a variable is deleted overwritten with a different value. This ticket is to implement such a behavior. It may save memory for applications that call setenv/unsetenv too often. There shouldn't be many apps like this so this task has a low priority.

A new implementation may track a shadow array with flags for each environment variable indicating if it was set by setenv and may be freed when overwritten etc. The new implementation may also speed up getenv operation considerably by using a hash map as a shadow array for environ.

See also getenv specs.