我想了解函数
getpwuid
从哪里分配内存。我有一些示例代码,可以打印输入到程序中的用户 ID 的用户名。
我阅读了
getpwuid
的手册页,内容是:
返回值可能指向静态区域,并且可能被覆盖 通过随后调用 getpwent(3)、getpwnam() 或 getpwuid()。 (做 不将返回的指针传递给 free(3)。)
我读到进程内存布局中的静态区域包含文本、初始化数据和未初始化数据。但返回的地址不在这些区域中的任何一个(据我所知 - 从
etext
,edata
和end
查看这些区域的边界)。
我有以下问题:
struct passwd
中的其他六个字段)分配内存。谁负责释放它?#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;
}
执行此程序后,会出现如下所示的内容:
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
man getpwuid
:
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).)