illwieckz

+1 Q_strncpyz hack

Apr 14th, 2016
203
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.80 KB | None | 0 0
  1. char *Q_strncpyz( char *dst, const char *src, size_t len ) {
  2.     if ( len == 0 ) {
  3.         abort();
  4.     }
  5.  
  6.     strncpy( dst, src, len );
  7.     dst[ len -1 ] = '\0';
  8.     return dst;
  9. }
  10.  
  11.  
  12. char *Q_strcat( char *dst, size_t dlen, const char *src ) {
  13.     size_t n = strlen( dst  );
  14.  
  15.     if ( n > dlen ) {
  16.         abort(); /* buffer overflow */
  17.     }
  18.  
  19.     return Q_strncpyz( dst + n, src, dlen - n );
  20. }
  21.  
  22.  
  23. char *Q_strncat( char *dst, size_t dlen, const char *src, size_t slen ) {
  24.     size_t n = strlen( dst );
  25.  
  26.     if ( n > dlen ) {
  27.         abort(); /* buffer overflow */
  28.     }
  29.  
  30.     // hack +1, that extra char outside slen will be rewritten by \0 by Q_strncpyz even if there is already a \0
  31.     // and if it's not a \0, we do not want to copy it but since it will be rewritten by \0 it's ok.
  32.     return Q_strncpyz( dst + n, src, MIN( slen + 1, dlen - n ) );
  33. }
Add Comment
Please, Sign In to add comment