OiO.lk Blog C# Where does `getpwuid` allocate memory from?
C#

Where does `getpwuid` allocate memory from?


I would like to understand where does the function getpwuid allocate memory from. I have some sample code that prints the username for the user id input to the program.

I read the manual page for getpwuid and is says:

The return value may point to a static area, and may be overwritten
by subsequent calls to getpwent(3), getpwnam(), or getpwuid(). (Do
not pass the returned pointer to free(3).)

I read that the static area in the memory layout of the process contains the text, initialized data and uninitialized data. But the returned address is not in any of these regions (as far as I can understand – from looking at the boundary of these regions from etext, edata and end).

I have the following questions:

  1. I’m unable to understand who is allocating memory for the username string (and the six other fields in struct passwd). Who is responsible for freeing it?
  2. How can the compiler possibly know how long the username, password and other fields are going to be, so it can allocate the memory statically?
#include <pwd.h>
#include <ctype.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

extern char etext, edata, end;

char* userNameFromId(uid_t uid)
{
    struct passwd *pwd;
    pwd = getpwuid(uid);
    return (pwd==NULL)?NULL:pwd->pw_name;
}

int main(int argc, char** argv)
{
    uid_t u;
    char* endptr = NULL;
    char* name;
    if(argc!=2){
        printf("Usage: %s [user_id]\n", argv[0]);
        return -1;
    }
    u = strtol(argv[1], &endptr, 10);
    if(*endptr!='\0') {
        printf("%s is not a number\nUsage: %s [user_id]\n", argv[1], argv[0]);
        return -1;
    }
    name = userNameFromId(u);
    if(name == NULL) {
        printf("No user was found with the given id: %s\n", argv[1]);
        return -1;
    }
    printf("program text ends before      %10p\n", &etext);
    printf("initialized data ends before  %10p\n", &edata);
    printf("uninitializd data ends before %10p\n", &end);
    printf("name is located at            %10p\n", &name);
    printf("program break is located at   %10p\n", sbrk(0));
    printf("User name for id %d is %s\n", u, name);
    return 0;
}

Upon executing this program pints something like the following:

ragav@DESKTOP-JJOG9GH:~$ ./a.out 1000
program text ends before      0x559fbcea23d5
initialized data ends before  0x559fbcea5010
uninitializd data ends before 0x559fbcea5018
name is located at            0x7ffc87a9f7f0
program break is located at   0x559fbd81b000
User name for id 1000 is ragav



You need to sign in to view this answers

Exit mobile version