mirror of
https://github.com/json-c/json-c.git
synced 2026-09-07 08:36:50 +08:00
printbuf: preserve self-append sources across growth
When the appended data points into the printbuf itself, growing the buffer may invalidate the source pointer before it is copied. Preserve the source offset across realloc and use memmove for internal overlap.
This commit is contained in:
@@ -126,6 +126,38 @@ static void test_printbuf_memappend(int *before_resize)
|
||||
printf("%s: end test\n", __func__);
|
||||
}
|
||||
|
||||
static void test_printbuf_self_append(void);
|
||||
static void test_printbuf_self_append(void)
|
||||
{
|
||||
struct printbuf *pb;
|
||||
char *data;
|
||||
int data_size;
|
||||
int i;
|
||||
int initial_size;
|
||||
|
||||
printf("%s: starting test\n", __func__);
|
||||
pb = printbuf_new();
|
||||
assert(pb != NULL);
|
||||
initial_size = pb->size;
|
||||
data_size = initial_size / 2 + 1;
|
||||
data = malloc(data_size);
|
||||
assert(data != NULL);
|
||||
memset(data, 'X', data_size);
|
||||
assert(printbuf_memappend(pb, data, data_size) == data_size);
|
||||
free(data);
|
||||
assert(pb->size == initial_size);
|
||||
|
||||
assert(printbuf_memappend(pb, pb->buf, pb->bpos) == data_size);
|
||||
assert(pb->size > initial_size);
|
||||
assert(pb->bpos == data_size * 2);
|
||||
for (i = 0; i < pb->bpos; i++)
|
||||
assert(pb->buf[i] == 'X');
|
||||
assert(pb->buf[pb->bpos] == '\0');
|
||||
|
||||
printbuf_free(pb);
|
||||
printf("%s: end test\n", __func__);
|
||||
}
|
||||
|
||||
static void test_sprintbuf(int before_resize);
|
||||
static void test_sprintbuf(int before_resize)
|
||||
{
|
||||
@@ -182,6 +214,8 @@ int main(int argc, char **argv)
|
||||
printf("========================================\n");
|
||||
test_printbuf_memappend(&before_resize);
|
||||
printf("========================================\n");
|
||||
test_printbuf_self_append();
|
||||
printf("========================================\n");
|
||||
test_sprintbuf(before_resize);
|
||||
printf("========================================\n");
|
||||
|
||||
|
||||
@@ -21,6 +21,9 @@ Append to just after resize: 32, [XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX]
|
||||
Buffer size after printbuf_strappend(): 16, [XXXXXXXXXXXXXXXX]
|
||||
test_printbuf_memappend: end test
|
||||
========================================
|
||||
test_printbuf_self_append: starting test
|
||||
test_printbuf_self_append: end test
|
||||
========================================
|
||||
test_sprintbuf: starting test
|
||||
Buffer length: 0
|
||||
sprintbuf to just after resize(31+1): 32, [XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX], strlen(buf)=32
|
||||
|
||||
Reference in New Issue
Block a user