Skip to content

Commit 00625f4

Browse files
lib/utmp.c: get_current_utmp(): Use the stack for temporary copies
As Evgeny reported, malloc(3) is overkill here. He suggested using other methods, which are less than ideal, but it's true that it's overkill, and with the stack we can get something readable and more efficient. Reported-by: Evgeny Grin (Karlson2k) <[email protected]> Signed-off-by: Alejandro Colomar <[email protected]>
1 parent cd4c864 commit 00625f4

File tree

1 file changed

+5
-13
lines changed

1 file changed

+5
-13
lines changed

lib/utmp.c

Lines changed: 5 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -158,9 +158,8 @@ get_current_utmp(pid_t main_pid)
158158
UT_MATCH_BY_PID_AND_LINE
159159
};
160160

161+
struct utmpx ut_copy;
161162
struct utmpx *ut;
162-
struct utmpx *ut_by_pid = NULL;
163-
struct utmpx *ut_by_line = NULL;
164163
enum ut_match match;
165164

166165
setutxent();
@@ -175,34 +174,27 @@ get_current_utmp(pid_t main_pid)
175174
if (main_pid == ut->ut_pid) {
176175
if (is_my_tty(ut->ut_line)) {
177176
match = UT_MATCH_BY_PID_AND_LINE;
177+
ut_copy = *ut;
178178
break;
179179
}
180180

181181
if (match < UT_MATCH_BY_PID) {
182182
match = UT_MATCH_BY_PID;
183-
ut_by_pid = xmalloc_T(1, struct utmpx);
184-
*ut_by_pid = *ut;
183+
ut_copy = *ut;
185184
}
186185

187186
} else if ( LOGIN_PROCESS == ut->ut_type /* Be more picky when matching by 'ut_line' only */
188187
&& is_my_tty(ut->ut_line))
189188
{
190189
if (match < UT_MATCH_BY_LINE) {
191190
match = UT_MATCH_BY_LINE;
192-
ut_by_line = xmalloc_T(1, struct utmpx);
193-
*ut_by_line = *ut;
191+
ut_copy = *ut;
194192
}
195193
}
196194
}
197195

198-
if (NULL == ut)
199-
ut = ut_by_pid ?: ut_by_line;
196+
ut = match ? memdup_T(&ut_copy, struct utmpx) : NULL;
200197

201-
if (NULL != ut)
202-
ut = memdup_T(ut, struct utmpx);
203-
204-
free(ut_by_line);
205-
free(ut_by_pid);
206198
endutxent();
207199

208200
return ut;

0 commit comments

Comments
 (0)