Reputation: 23
Since sprintf will cause some buffer overflow, I need to change all sprintf to snprintf in project. But I got some trouble as following:
void foo( char *a, uchar *string)
{
sprintf(string, 'format', src_str);
}
The question is when the destination string is a parameter of the function, how to decide the buffer size or the maximum length of string after we change to snprintf..
Upvotes: 2
Views: 1418
Reputation: 5557
If you have the option to allocate the destination-buffer yourself, you can check the length of the source string with strlen()
in case it is null-terminatd and allocate a sufficiently large buffer for it and the terminating null-character. You could also use asprintf
directly, if it is available.
If you do not have that option you will have to pass the size of the destination buffer as argument, because you cannot reliably determine its size from inside the function if you only have the pointer to it (unless the destination buffer is always delimited in a uniquely identifiable way).
Upvotes: 2
Reputation: 95355
You will not gain any benefit by simply changing out sprintf
for snprintf
if you are not able to call snprintf
with the proper arguments. Your foo
function needs to also take an extra parameter just like snprintf
requires an extra parameter over sprintf
. Since arrays decay to pointers when they are used as arguments to a function, any size information is lost.
This may be a pain in the arse if you call foo
hundreds of times throughout your program, but if you want to make sure you avoid buffer overruns, you need to make sure that any functions that operate on arrays are fully aware of their size.
If you are using GCC or clang, you can put a deprecation warning on the foo
function by changing its prototype to1:
void __attribute__((deprecated)) foo(char *a, uchar *string);
Then, you can create a new function, e.g. foo_n
, which has the extra parameter for the size. When you compile your code, GCC will emit a warning for each use of the function foo
, so you know to replace them with foo_n
.
1. It's possible that the __attribute__((deprecated))
part goes after the parameter list, but clang seems to accept it as it is shown above.
Upvotes: 0
Reputation: 64700
Calling _scprintf(...) will tell you how big the string would be, without actually using a buffer.
Then you allocate a buffer of that size, and call snprintf.
Upvotes: 0