c++ - snprintf() returning inappropriate value -


i've been looking on piece of code while, , can't seem find bug. think know how snprintf(dest, n, fmt, src) supposed work ( returns number of remaining characters in src buffer after filling dest buffer n characters fmt string , src buffer) not doing expect. instead of returning number of remaining characters copied, returning total characters copied.

the code below:

 40   char header_file_name[200];  ....  87   int n_overflow = 0;  88   n_overflow = snprintf( header_file_name, 200, "%s.h", template_name );  89   if ( n_overflow > 0 )  90   {  91       printf( "that template name large; try smaller template name\n");  92       printf("n_overflow = %d\n", n_overflow);  93       printf("header_file_name = %s\n", header_file_name );  94       printf("length of header_file_name = %d\n", strlen(header_file_name));  95       printf( "template_name = %s\n", template_name );  96       printf("length of template_name = %d\n", strlen(template_name));  97       exit(4);  98   }  99   if ( n_overflow < 0 ) 100   { 101       printf( "an error occurred while handling input; file: %s, line:%d\n", __file__, __line__); 102       exit(1); 103   } 

outputs following:

compiling template file abaqus_version_5.template template name large; try smaller template name n_overflow = 18 header_file_name = abaqus_version_5.h length of header_file_name = 18 template_name = abaqus_version_5 length of template_name = 16 *** error code 4 clearmake: error: build script failed "abaqus_version_5.o" 

what makes confusing dest (header_file_name) has length, , has data in after snprintf() call, , src (template_name) has length , not null. i've made gaff in code, or don't understand snprintf(), , have been starring @ long. assistance appreciated!

that's snprintf supposed do.

from man snprintf on ubuntu system: (emphasis added)

the functions snprintf() , vsnprintf() not write more size bytes (including terminating null byte ('\0')). if output truncated due limit return value number of characters (excluding terminating null byte) would have been written final string if enough space had been available. thus, return value of size or more means output truncated.

or, simpler wording posix:

upon successful completion, snprintf() function shall return number of bytes written s had n been sufficiently large excluding terminating null byte.


Comments

Popular posts from this blog

java - Spring Data JPA: Why findOne(id) executing delete query internally? -

python - Mongodb How to add addtional information when aggregating? -

java - Incorrect order of records in M-M relationship in hibernate -