1

I am trying to update a password structure in a function. This function gets a pointer to password structure, into which I have to update details.

I get a struct passwd* to a function as an argument and my requirement is to update it's members to someother user's(user2) information and caller of this function should have all these updated details.

I tried following, can you please help me by suggesting what is an ideal way to do it.

My function is like this:

struct passwd* myfunc(struct passwd *pw)

To this pw, I have to update details.

Try1:

Using getpwnam() get details of user2 into passed struct passwd *pw.

pw = getpwnam("user2");
return pw;

Does not work, as we are not updating pw members rather we are just pointing pw to some other struct, pointer members of pw, still point to older data. And thus parent of myfunc() does not get updated details.

We have to write into members.

Try2:

Using getpwnam() get details of user2 into a temp struct passwd*. Do a memcpy(pw, temppasswd, sizeof(struct passwd))

Does not work as memcpy is a shallow copy and consequent getpwnam() (although the return is not given to temppasswd) will over write static buffer area, and pw may have different values.

Try3:

Tried getpwnam_r() which writes details into buffer passed as an argument to it rather than into a static data area (like getpwnam).

Can not use this, as I don't have pw, I have *pw. So, I can not pass address of memory allocated to pw to getpwnam_r.

Try 4:

I can do member by member copy in Try2, but it can result in memory leaks if I don't free pw structure pointer members before copying data into them.

Is there any other way to copy details to passed pw* without free-ing all struct pw* pointer members.

It is a bit confusing, I hope I make sense to someone.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
Ram
  • 1,153
  • 4
  • 16
  • 34

1 Answers1

0

You could combine the first two alternatives as *pw = *getpwnam("user2");. It's still a shallow copy though.

As for your problem, if you can change the prototype to struct passwd* myfunc(struct passwd **pw) then you could allocate the structure and all needed fields yourself. Then have a separate function that the user must call to free all allocated data.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621