Subject: Re: [PATCH v4] mailinfo: fix pointential memory leak if `decode_header` failed

From: Junio C Hamano <[email-masked]>
Date: Tue, 13 May 2025 06:34:21 -0700

"Lidong Yan via GitGitGadget" <[email-masked]> writes:

> -static struct strbuf *decode_q_segment(const struct strbuf *q_seg, int rfc2047)
> +static int decode_q_segment(struct strbuf *out, const struct strbuf *q_seg,
> +			    int rfc2047)
>  {
>  	const char *in = q_seg->buf;
>  	int c;
> -	struct strbuf *out = xmalloc(sizeof(struct strbuf));
> -	strbuf_init(out, q_seg->len);
> +	strbuf_grow(out, q_seg->len);

Call to grow(), while it does not hurt correctness, would not be
necessary here, but let's take this code as-is.  As the result of Q
encoding (and B encoding as well) always is longer than the decoded
result, strbuf_grow(out, q_seg->len) would always be over-allocating,
but it would not hurt too much.

> -static struct strbuf *decode_b_segment(const struct strbuf *b_seg)
> +static int decode_b_segment(struct strbuf *out, const struct strbuf *b_seg)
>  {
>  	/* Decode in..ep, possibly in-place to ot */
>  	int c, pos = 0, acc = 0;
>  	const char *in = b_seg->buf;
> -	struct strbuf *out = xmalloc(sizeof(struct strbuf));
> -	strbuf_init(out, b_seg->len);
> +	strbuf_grow(out, b_seg->len);

Ditto.

>  	char *in, *ep, *cp;
> -	struct strbuf outbuf = STRBUF_INIT, *dec;
> +	struct strbuf outbuf = STRBUF_INIT, dec = STRBUF_INIT;
>  	struct strbuf charset_q = STRBUF_INIT, piecebuf = STRBUF_INIT;
>  	int found_error = 1; /* pessimism */

The remainder of the patch also looks good.

Thanks.