9

After I call getpwuid(uid), I have a reference to a pointer. Should I free that pointer when I don't use it anymore? Reading the man pages, it says that it makes reference to some static area, that may be overwritten by subsequent calls to the same functions, so I'm not sure if I should touch that memory area.

Thanks.

Guy Avraham
  • 3,482
  • 3
  • 38
  • 50
Gabriel
  • 2,313
  • 9
  • 29
  • 41

3 Answers3

12

No. You do not need to free the result. You can only call free(3) on pointers allocated on the heap with malloc(3), calloc(3) or realloc(3).

Static data is part of a program's data or bss segments and will persist until the process exits (or is overwritten by exec(2)).

camh
  • 40,988
  • 13
  • 62
  • 70
  • So once loaded, these passwd structs just stay around indefinitely? Isn't that a memory leak? – Alexander May 11 '20 at 01:29
  • 1
    @Alexander-ReinstateMonica No, it is a single piece of static data, that will be overwritten on each call to `getpwuid`. Which is why it is not thread-safe / reentrant. A memory leak is when you allocate dynamic memory and never free it. – camh May 11 '20 at 06:48
  • Ah yes, that makes sense. And so I assume that `getpwuid` cleans up the old string pointers, before assigning new ones – Alexander May 11 '20 at 12:14
  • 1
    I believe it maintains a malloc'ed buffer that it reallocs to grow if it needs to. It reads the password entry into that buffer and sets the pointers to point into that. The buffer would get overwritten on subsequent calls to `getpwuid`. https://elixir.bootlin.com/glibc/latest/source/nss/getXXbyYY.c is the implementation (as a template of sorts). – camh May 11 '20 at 12:49
5

Use the *_r functions (getpwuid_r()) for thread-safe (reentrant) functions that allow you to supply the buffer space to place the returned information in. Be sure check errno for success or failure. If you do not use reentrant functions you can safely assume that the function returns data that does not need to be freed, but will also be overwritten by successive calls to the same function.

Steve Baker
  • 4,323
  • 1
  • 20
  • 15
1

Actually it returns a pointer to an already existing structure, so you should not free it.

dguaraglia
  • 5,774
  • 1
  • 26
  • 23