我有一个功能:
func (struct passwd* pw)
{
struct passwd* temp;
struct passwd* save;
temp = getpwnam("someuser");
/* since getpwnam returns a pointer to a static
* data buffer, I am copying the returned struct
* to a local struct.
*/
if(temp) {
save = malloc(sizeof *save);
if (save) {
memcpy(save, temp, sizeof(struct passwd));
/* Here, I have to update passed pw* with this save struct. */
*pw = *save; /* (~ memcpy) */
}
}
}
调用func(pw)的函数能够获取更新的信息。
但如上所述可以使用它。 声明* pw = * save不是深层副本。 我不想像逐个复制每个结构的每个成员 pw-> pw_shell = strdup(save-> pw_shell)等。
有没有更好的方法呢?
感谢。
答案 0 :(得分:1)
函数参数必须为struct passwd**
,然后更改*passwd
答案 1 :(得分:1)
如果你愿意,你可以做一个浅拷贝,但结果只有在下次调用getpenam之前才会有效。但为什么要复制两次?你的malloc是内存泄漏!这样做会很好:
void func (struct passwd *pw)
{
struct passwd *tmp = getpenam("someuser"); // get a pointer to a static struct
*pw = *tmp; // copy the struct to caller's storage.
}
如果您需要深层复制,则必须逐字段进行:
void deep_func (struct passwd *pw)
{
struct passwd *tmp = getpenam("someuser"); // get a pointer to a static struct
*pw = *tmp; // copy everything
pw->pw_name = safe_strdup(pw->pw_name); // Copy pointer contents.
pw->pw_passwd = safe_strdup(pw->pw_passwd);
// etc for all pointer fields
}
对于深层复制,您需要一个相应的例程来释放malloc()'ed storage:
void free_passwd_fields(struct passwd *pw)
{
free(pw->pw_name);
free(pw->pw_passwd);
// etc
}
进行通话的好方法是:
// Declare a 1-element array of structs.
// No &'s are needed, so code is simplified, and a later change to malloc()/free() is very simple.
struct passwd pw[1];
// ... and later
func(pw);
// pw now behaves like a pointer to a struct, but with no malloc or free needed.
// For example:
printf("login name is %s\n", pw->pw_name);
// Done with copy. Free it.
free_passwd_fields(pw);