Skip to content

Commit 193134b

Browse files
committed
Implement string assembly with stpcpy
The audit_encode_nv_string helper no longer relies on asprintf and instead uses pre‑computed lengths to assemble the string directly.
1 parent a7441f8 commit 193134b

File tree

1 file changed

+35
-15
lines changed

1 file changed

+35
-15
lines changed

lib/audit_logging.c

Lines changed: 35 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -123,25 +123,45 @@ char *audit_encode_value(char *final, const char *buf, unsigned int size)
123123
}
124124

125125
char *audit_encode_nv_string(const char *name, const char *value,
126-
unsigned int vlen)
126+
unsigned int vlen)
127127
{
128-
char *str;
128+
size_t nlen, len;
129+
char *str, *ptr;
130+
int encode = 0;
129131

130-
if (vlen == 0 && value)
132+
if (value == NULL) {
133+
value = "?";
134+
vlen = 1;
135+
}
136+
137+
if (vlen == 0)
131138
vlen = strlen(value);
132139

133-
if (value && audit_value_needs_encoding(value, vlen)) {
134-
char *tmp = malloc(2*vlen + 1);
135-
if (tmp) {
136-
audit_encode_value(tmp, value, vlen);
137-
if (asprintf(&str, "%s=%s", name, tmp) < 0)
138-
str = NULL;
139-
free(tmp);
140-
} else
141-
str = NULL;
142-
} else
143-
if (asprintf(&str, "%s=\"%s\"", name, value ? value : "?") < 0)
144-
str = NULL;
140+
nlen = strlen(name);
141+
142+
if (audit_value_needs_encoding(value, vlen)) {
143+
encode = 1; // name + '=' + 2*value len + termination
144+
len = nlen + 1 + (2 * vlen) + 1;
145+
} else // name + 2 double quotes + value + termination
146+
len = nlen + 2 + vlen + 1;
147+
148+
str = malloc(len);
149+
if (str == NULL)
150+
return NULL;
151+
152+
ptr = stpcpy(str, name);
153+
*ptr++ = '=';
154+
155+
if (encode)
156+
audit_encode_value(ptr, value, vlen);
157+
else {
158+
*ptr++ = '"';
159+
memcpy(ptr, value, vlen);
160+
ptr += vlen;
161+
*ptr++ = '"';
162+
*ptr = '\0';
163+
}
164+
145165
return str;
146166
}
147167

0 commit comments

Comments
 (0)