tags:

views:

288

answers:

2

Is there a fix or a workaround for the memory leak in getpwnam?

+3  A: 

Use getpwnam_r.

Paul Tomblin
+6  A: 

getpwnam() does not suffer of memory leak. Subsequent calls, indeed, will overwrite its static internal buffer.

Such kind of functions are instead non-reentrant and therefore non-thread safe. Paul suggested the use of getpwnam_r() which is the reentrant version, that is safe to be used in a multithread context.

That said, memory leaks are caused by those system calls that allocate memory by means of malloc() and leave the application the responsability to free() the memory once the returned data has used.

In these cases the RAII idiom is advisable in order to not forget to free the allocated memory -- see exception safety. std::tr1::shared_ptr<> is also a viable way: For the shared_ptr a custom deleter must be provided to free() the raw pointer when the shared_ptr goes out of the scope.

Under this perspective some dangerous functions are scandir(), asprintf(), vasprintf() etc.

Nicola Bonelli
Oh good answer. If I could transfer the "accepted answer" to you, I would.
Paul Tomblin
@Nicola, thank you, marking your answer as accepted