Fix malloc/tst-scratch_buffer

The test used scratch_buffer_dupfree incorrectly:

- The passed in size must be <= buf.length.
- Must be called at most once on a buf object since it frees it.
- After it is called buf.data and buf.length must not be accessed.

All of these were violated, the test happened to work because the
buffer was on the stack, which meant the test copied out-of-bounds
bytes from the stack into a new buffer and then compared those bytes.

Run one test and avoid the issues above.
This commit is contained in:
Szabolcs Nagy 2022-10-11 13:23:25 +01:00
parent 37cfa707b0
commit fbc8167346

View File

@ -155,21 +155,13 @@ do_test (void)
struct scratch_buffer buf;
scratch_buffer_init (&buf);
memset (buf.data, '@', buf.length);
size_t sizes[] = { 16, buf.length, buf.length + 16 };
for (int i = 0; i < array_length (sizes); i++)
{
/* The extra size is unitialized through realloc. */
size_t l = sizes[i] > buf.length ? sizes[i] : buf.length;
void *r = scratch_buffer_dupfree (&buf, l);
void *c = xmalloc (l);
memset (c, '@', l);
TEST_COMPARE_BLOB (r, l, buf.data, l);
free (r);
free (c);
}
scratch_buffer_free (&buf);
size_t l = 16 <= buf.length ? 16 : buf.length;
void *r = scratch_buffer_dupfree (&buf, l);
void *c = xmalloc (l);
memset (c, '@', l);
TEST_COMPARE_BLOB (r, l, c, l);
free (r);
free (c);
}
return 0;
}