fix bogus lazy allocation in ctermid and missing malloc failure check

also clean up, optimize, and simplify the code, removing branches by
simply pre-setting the result string to an empty string, which will be
preserved if other operations fail.
This commit is contained in:
Rich Felker 2013-07-09 00:50:11 -04:00
commit b6218764eb

View file

@ -8,17 +8,14 @@
char *ctermid(char *s) char *ctermid(char *s)
{ {
static char *s2; static char s2[L_ctermid];
int fd; int fd;
if (!s) { if (!s) s = s2;
if (!s2) s2 = malloc(L_ctermid); *s = 0;
s = s2;
}
fd = open("/dev/tty", O_WRONLY | O_NOCTTY | O_CLOEXEC); fd = open("/dev/tty", O_WRONLY | O_NOCTTY | O_CLOEXEC);
if (fd < 0) if (fd >= 0) {
return strcpy(s, ""); ttyname_r(fd, s, L_ctermid);
if (ttyname_r(fd, s, L_ctermid)) __syscall(SYS_close, fd);
strcpy(s, ""); }
__syscall(SYS_close, fd);
return s; return s;
} }