cvs: php4 /main snprintf.h

From: Date: Sun, 23 Jun 2002 22:16:35 +0000
Subject: cvs: php4 /main snprintf.h
Groups: php.cvs 
Request: Send a blank email to php-cvs+get-12472@lists.php.net to get a copy of this message
helly Sun Jun 23 18:16:35 2002 EDT Modified files: /php4/main snprintf.h Log: 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 Index: php4/main/snprintf.h diff -u php4/main/snprintf.h:1.17 php4/main/snprintf.h:1.18 --- php4/main/snprintf.h:1.17 Tue May 7 09:24:07 2002 +++ php4/main/snprintf.h Sun Jun 23 18:16:35 2002 @@ -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

« previous php.cvs (#12472) next »