Skip to content

Commit 0d487a6

Browse files
committed
Defensively terminate the output buffer on error.
Suggested by Scott
1 parent 4ae257e commit 0d487a6

3 files changed

Lines changed: 16 additions & 0 deletions

File tree

include/re/groups.h

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,9 @@ struct re_pos;
4444
*
4545
* outs may be NULL in which case outn must be 0, and no
4646
* output is made.
47+
*
48+
* On error the function returns false and the output
49+
* buffer is indeterminate.
4750
*/
4851
bool
4952
re_interpolate_groups(const char *fmt, char esc,

src/libre/re_interpolate_groups.c

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@ re_interpolate_groups(const char *fmt, char esc,
3737
struct re_pos *start, struct re_pos *end)
3838
{
3939
unsigned group; // 0 meaning group0, 1 meaning groupv[0], etc
40+
char *outs_orig;
4041
const char *p;
4142

4243
enum {
@@ -53,6 +54,8 @@ re_interpolate_groups(const char *fmt, char esc,
5354
state = STATE_LIT;
5455
group = 0;
5556

57+
outs_orig = outn > 0 ? outs : NULL;
58+
5659
if (start != NULL) {
5760
start->byte = 0;
5861
}
@@ -186,6 +189,10 @@ re_interpolate_groups(const char *fmt, char esc,
186189
end->byte = p - fmt;
187190
}
188191

192+
if (outs_orig != NULL) {
193+
*outs_orig = '\0';
194+
}
195+
189196
return false;
190197
}
191198

tests/re_interpolate_groups/re_interpolate_groups1.c

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,13 +24,19 @@ test_err(const char *fmt, size_t groupc, const char *groupv[], const char *ne,
2424

2525
assert(fmt != NULL);
2626

27+
outs[0] = 'x';
28+
2729
/* for these tests we're expecting to error */
2830
if (re_interpolate_groups(fmt, '$', "<g0>", groupc, groupv, ne, outs, sizeof outs, &start, &end)) {
2931
printf("%s/%zu XXX\n", fmt, groupc);
3032
failed++;
3133
return;
3234
}
3335

36+
if (outs[0] != '\0') {
37+
failed++;
38+
}
39+
3440
failed += rs = expected_start != start.byte;
3541
failed += re = expected_end != end.byte;
3642

0 commit comments

Comments
 (0)