Skip to content

[Bug] Replace use of sprintf() and vsprintf() in C code #5568

Description

@nilason

Replace use of sprintf() and vsprintf() in C code, their use is considered dangerous:

GNU C Library

Warning: The sprintf function can be dangerous because it can potentially output more characters than can fit in the allocation size of the string s. Remember that the field width given in a conversion specification is only a minimum value.

Linux

Because sprintf() and vsprintf() assume an arbitrarily long string, callers must be careful not to overflow the actual space; this is often impossible to assure. Note that the length of the strings produced is locale-dependent and difficult to predict. Use snprintf() and vsnprintf() instead (or asprintf(3) and vasprintf(3)).

BSD based platforms, see FreeBSD

The sprintf() and vsprintf() functions are easily misused in manner which enables malicious users to arbitrarily change a running program's functionality through a buffer overflow attack. Because sprintf() and vsprintf() assume an infinitely long string, callers must be careful not to overflow the actual space; this is often hard to assure. For safety, programmers should use the snprintf() interface instead.

It is suggested that sprintf() should be replaced with snprintf(), which in general is a trivial task. One important issue to bear in mind, is the difference of how to set the buffer size depending on using a fixed-size or a dynamically allocated buffer:

// fixed-size buffer:
char onstack[8];
snprint(onstack, sizeof(onstack), format_string, arguments)

// dynamically allocated buffer:
size_t len = strlen(a_string) + 1;
char *heap_buf = G_malloc(len);
snprintf(heap_buf, len, "%s", a_string);

This is bad code:

char *heap_buf = G_malloc(len);
snprintf(heap_buf, sizeof(heap_buf), "%s", a_string);

as sizeof(heap_buf) gives the size of the pointer, not the size of the array.

This issue is a continuation of #2766, which was focused on C++ code.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions