c++ - How to achieve strncpy() functionality with strncpy_s() function? -


there're cases when need strncpy() funcitonalty - example have function in predefined interface passed address of buffer , size of buffer:

hresult somefunction( char* buffer, size_t length ); 

and documented can copy null-terminated string there length no more length - if of length length don't null-terminate string , caller knows string ends @ either null character or @ length length whichever happens first , works.

of course use strncpy() that

hresult somefunction( char* buffer, size_t length ) {     const char* tocopy = ...     size_t actuallength = strlen( tocopy );     if( actuallength > length ) {         return e_unexpected; // doesn't fit, can't reasonable      }     strncpy( buffer, tocopy, length );     return s_ok; } 

now have code , need migrate visual c++ 7 visual c++ 9. compile , see warning strncpy() unsafe , should instead use strncpy_s().

strncpy_s() designed null-terminate buffer, can't use direct replacement in above scenario. i'll have return e_unexpected on strings longer length - 1 (not length previously) or fire invalid parameters error handler once string of length or longer or program run undefined behavior.

the solution applied far define _crt_secure_no_warnings , make compiler shut up.

is there way use strncpy_s() actual replacement strncpy()?

the problem you're facing here function unsafe in itself, strncpy() is. unsafe because callers of function might forget returned strings not null terminated. if desired behavior of function recommend not define _crt_secure_no_warnings , disable warnings globally use #pragmas instead:

// document here why can not use strncpy_s #pragma warning( push ) #pragma warning( disable : 4996 ) // code uses strncpy instead of strncpy_s #pragma warning( pop )  

that way disable warnings situations absolutely have use unsafe functions.


Comments

Popular posts from this blog

apache - Add omitted ? to URLs -

redirect - bbPress Forum - rewrite to wwww.mysite prohibits login -

php - How can I stop spam on my custom forum/blog? -