Avoid using sprintf(), vsprintf(), strcat(), and strncat().
It is less error-prone to use functions with a return value that indicates when truncation ocurred.
This commit is contained in:
@@ -141,31 +141,23 @@ char *
|
||||
str_replaced(const char *source, size_t dest_len, const char *old, const char *new)
|
||||
{
|
||||
char *result = calloc(1, dest_len);
|
||||
char *dest = result;
|
||||
char *pos = NULL;
|
||||
size_t old_len = strlen(old);
|
||||
size_t new_len = strlen(new);
|
||||
size_t available_len = dest_len;
|
||||
|
||||
while ((pos = strstr(source, old)) != NULL) {
|
||||
size_t skipped_len = (size_t)(pos - source);
|
||||
if (available_len <= skipped_len + 1)
|
||||
size_t len = snprintf(dest, dest_len,
|
||||
"%.*s%s", (int)(pos - source), source, new);
|
||||
if (len >= dest_len)
|
||||
goto fail;
|
||||
|
||||
available_len -= skipped_len;
|
||||
strncat(result, source, skipped_len);
|
||||
|
||||
if (available_len <= new_len + 1)
|
||||
goto fail;
|
||||
|
||||
available_len -= new_len;
|
||||
strcat(result, new);
|
||||
|
||||
dest_len -= len;
|
||||
dest += len;
|
||||
source = pos + old_len;
|
||||
}
|
||||
|
||||
if (available_len <= strlen(source) + 1)
|
||||
if (strlcpy(dest, source, dest_len) >= dest_len)
|
||||
goto fail;
|
||||
strcat(result, source);
|
||||
|
||||
return result;
|
||||
|
||||
|
@@ -44,12 +44,11 @@ const char *
|
||||
expected_path(const char *format, ...)
|
||||
{
|
||||
static char expected_output_file[PATH_MAX];
|
||||
int count = snprintf(expected_output_file, PATH_MAX, TESTDATA_DIR);
|
||||
char *filename = expected_output_file + count;
|
||||
size_t dirlen = strlcpy(expected_output_file, TESTDATA_DIR, sizeof(expected_output_file));
|
||||
|
||||
va_list args;
|
||||
va_start(args, format);
|
||||
vsprintf(filename, format, args);
|
||||
vsnprintf(expected_output_file + dirlen, PATH_MAX - dirlen, format, args);
|
||||
va_end(args);
|
||||
|
||||
return expected_output_file;
|
||||
@@ -213,10 +212,9 @@ verify_log_lines(const char *reference_path)
|
||||
|
||||
char *line_end = strstr(line_data, " object at "); // this skips checking the pointer hex
|
||||
if (line_end)
|
||||
sprintf(line_end, " object>\n");
|
||||
snprintf(line_end, sizeof(line) - (line_end - line), " object>\n");
|
||||
|
||||
VERIFY_TRUE(strlen(stored_str) + strlen(line_data) + 1 < sizeof(stored_str)); // we have enough space in buffer
|
||||
strcat(stored_str, line_data);
|
||||
VERIFY_TRUE(strlcat(stored_str, line_data, sizeof(stored_str)) < sizeof(stored_str)); // we have enough space in buffer
|
||||
}
|
||||
|
||||
clean_output(stored_str);
|
||||
|
Reference in New Issue
Block a user