'strncpy' vs. 'sprintf'

后端 未结 4 1223
萌比男神i
萌比男神i 2021-01-31 06:01

I can see many sprintf\'s used in my applications for copying a string.

I have a character array:

char myarray[10];
const char *str = \"myst         


        
4条回答
  •  失恋的感觉
    2021-01-31 06:26

    There is one way to use sprintf() (or if being paranoid, snprintf() ) to do a "safe" string copy, that truncates instead of overflowing the field or leaving it un-NUL-terminated.

    That is to use the "*" format character as "string precision" as follows:

    So:

    char dest_buff[32];
    ....
    sprintf(dest_buff, "%.*s", sizeof(dest_buff) - 1, unknown_string);
    

    This places the contents of unknown_string into dest_buff allowing space for the terminating NUL.

提交回复
热议问题