From: Marcus Boerger Date: Sun, 23 Jun 2002 22:16:35 +0000 (+0000) Subject: explain difference between sprintf, snprintf and spprintf X-Git-Tag: php-4.3.0dev_zend2_alpha2~129 X-Git-Url: https://granicus.if.org/sourcecode?a=commitdiff_plain;h=302bfefac729e091673434e4616f6710583da327;p=php 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 --- diff --git a/main/snprintf.h b/main/snprintf.h index 767ce4e0c2..f6d7e36e05 100644 --- a/main/snprintf.h +++ b/main/snprintf.h @@ -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