File: testSnprintf.cpp

package info (click to toggle)
between 6%2Bdfsg1-2
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 3,532 kB
  • sloc: cpp: 28,110; php: 718; ansic: 638; objc: 245; sh: 236; makefile: 97; perl: 67
file content (58 lines) | stat: -rw-r--r-- 1,236 bytes parent folder | download | duplicates (30)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
/*
 * Modification History
 *
 * 2004-January-15   Jason Rohrer
 * Created.
 */

/**
 * A test program for snprintf behavior.
 */


#include <stdio.h>
#include <stdlib.h>
#include <string.h>



int main() { 
    int numStrings = 3;
    
    // test strings of length 3, 4, and 5
    const char *testStrings[3] = { "tst", "test", "testt" };

    int result;
    
    // a buffer of length 4, which IS NOT large
    // enough to hold the last two testStrings
    char *buffer = (char*)( malloc( 4 ) );

    int i;
    
    for( i=0; i<numStrings; i++ ) {
        // clear buffer with 'a' characters
        memset( (void*)buffer, (int)( 'a' ), 4 );
    
        // print testStringA into buffer
        result = snprintf( buffer, 4, "%s", testStrings[i] );

        printf( "Printed string of length %d to buffer of "
                "size 4 with snprintf.\n"
                "Return value = %d\n",
                strlen( testStrings[i] ),
                result );

        if( buffer[3] == '\0' ) {
            printf( "Buffer was null-terminated by snprintf\n\n" );
            }
        else {
            printf( "Buffer was NOT null-terminated by snprintf\n\n" );
            }
        }

    free( buffer );
    
    return 0;
}