mirror of
https://github.com/php/php-src.git
synced 2025-08-16 05:58:45 +02:00
explain difference between sprintf, snprintf and spprintf
#before complaining snprintf is often used wrong: #snprintf does not terminate the buffer but most people expect it #that could be a security isuue at somewhere
This commit is contained in:
parent
02ac908307
commit
302bfefac7
1 changed files with 43 additions and 0 deletions
|
@ -16,6 +16,49 @@
|
|||
+----------------------------------------------------------------------+
|
||||
*/
|
||||
|
||||
/*
|
||||
|
||||
Comparing: sprintf, snprintf, spprintf
|
||||
|
||||
sprintf offers the ability to make a lot of failures since it does not know
|
||||
the size of the buffer it uses. Therefore usage of sprintf often
|
||||
results in possible entries for buffer overrun attacks. So please
|
||||
use this version only if you are sure the call is safe. sprintf
|
||||
allways terminstes the buffer it writes to.
|
||||
|
||||
snprintf knows the buffers size and will not write behind it. But you will
|
||||
have to use either a static buffer or allocate a dynamic buffer
|
||||
before beeing able to call the function. In other words you must
|
||||
be sure that you really know the maximum size of the buffer required.
|
||||
A bad thing is having a big maximum while in most cases you would
|
||||
only need a small buffer. If the size of the resulting string is
|
||||
longer or equal to the buffer size than the buffer is not terminated.
|
||||
|
||||
spprintf is the dynamical version of snprintf. It allocates the buffer in size
|
||||
as needed and allows a maximum setting as snprintf (turn this feature
|
||||
off by setting max_len to 0). spprintf is a little bit slower than
|
||||
snprintf and offers possible memory leakes if you miss freeing the
|
||||
buffer allocated by the function. Therfore this function should be
|
||||
used where either no maximum is known or the maximum is much bigger
|
||||
than normal size required. spprintf allways terminates the buffer.
|
||||
|
||||
Example:
|
||||
|
||||
#define MAX 1024 | #define MAX 1024 | #define MAX 1024
|
||||
char buffer[MAX] | char buffer[MAX] | char *buffer;
|
||||
| |
|
||||
| | // No need to initialize buffer:
|
||||
| | // spprintf ignores value of buffer
|
||||
sprintf(buffer, "test"); | snprintf(buffer, MAX, "test"); | spprintf(&buffer, MAX, "text");
|
||||
| | if (!buffer)
|
||||
| | return OUT_OF_MEMORY
|
||||
// sprintf allways terminates | // manual termination of | // spprintf allays terminates buffer
|
||||
// buffer | // buffer *IS* required |
|
||||
| buffer[MAX-1] = 0; |
|
||||
action_with_buffer(buffer); | action_with_buffer(buffer); | action_with_buffer(buffer);
|
||||
| | efree(buffer);
|
||||
*/
|
||||
|
||||
#ifndef SNPRINTF_H
|
||||
#define SNPRINTF_H
|
||||
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue