1

我有一个功能:

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) 等一一复制结构的每个成员。

有没有更好的方法呢?

谢谢。

4

2 回答 2

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() 的存储:

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);
于 2012-11-14T05:08:22.703 回答
1

函数参数需要是struct passwd**,然后改变*passwd

于 2012-11-14T05:00:11.273 回答