Avoid writing to a zero-capacity buffer.

Bug: http://b/120752721
Test: ran tests
Change-Id: I3f03ae204ab5de40fd4402a5562c50ffe51ef998
This commit is contained in:
Elliott Hughes 2019-02-05 15:00:13 -08:00
parent 5c45c4efb2
commit 288465d6e9
2 changed files with 11 additions and 1 deletions

View file

@ -149,7 +149,9 @@ FILE* fmemopen(void* buf, size_t capacity, const char* mode) {
} else if (mode[0] == 'w') {
ck->size = 0;
ck->offset = 0;
ck->buf[0] = '\0';
if (capacity > 0) {
ck->buf[0] = '\0';
}
}
return fp;

View file

@ -1820,6 +1820,14 @@ TEST(STDIO_TEST, fmemopen_zero_length) {
ASSERT_EQ(0, fclose(fp));
}
TEST(STDIO_TEST, fmemopen_zero_length_buffer_overrun) {
char buf[2] = "x";
ASSERT_EQ('x', buf[0]);
FILE* fp = fmemopen(buf, 0, "w");
ASSERT_EQ('x', buf[0]);
ASSERT_EQ(0, fclose(fp));
}
TEST(STDIO_TEST, fmemopen_write_only_allocated) {
// POSIX says fmemopen "may fail if the mode argument does not include a '+'".
// BSD fails, glibc doesn't. We side with the more lenient.