EverEffects Backup Forum
Welcome To We Can't Program Forums, Please Log In To Access All Forums.

Enjoy Your Stay

- Staff

EverEffects Backup Forum

Designers World
 
HomePortalMemberlistRegisterLog in



 


Share | 
 

 Avoiding buffer overflows - strlcpy and strlcat - C++

View previous topic View next topic Go down 
AuthorMessage
Fred
Staff
Staff
avatar

Posts : 33
Join date : 2010-05-27
Age : 25
Location : Oklahoma

PostSubject: Avoiding buffer overflows - strlcpy and strlcat - C++   Thu Jun 03, 2010 5:25 pm
Here is a source code for avoiding buffer overflows. Also for those who uses Win32 programing with C. this file will be useful for you c++ users


Code:
#include <string.h>

size_t strlcpy(char *d, const char *s, size_t bufsize)
{
   size_t len;
   size_t ret;
   
   if (!d || !s) return 0;
   len = strlen(s);
   ret = len;
   if (bufsize <= 0) return 0;
   if (len >= bufsize) len = bufsize-1;
   memcpy(d, s, len);
   d[len] = 0;
   
   return ret;
}

size_t strlcat(char *d, const char *s, size_t bufsize)
{
   size_t len1;
   size_t len2;
   size_t ret;
   
   if (!d || !s || bufsize <= 0) return 0;
   
   len1 = strlen(d);
   len2 = strlen(s);
   ret = len1 + len2;
   if (len1+len2 >= bufsize)
   {
      len2 = bufsize - (len1+1);
   }
   if (len2 > 0)
   {
      memcpy(d+len1, s, len2);
      d[len1+len2] = 0;
   }
   return ret;

More on buffer overflows - MSVC's _snprintf function

Code:
size_t strllen(const char *string)
{
   if (!string) return 0;
   return strlen(string);

These are for "Unix" and "MSVC".

Unix: The snprintf() function will write at most size-1 of the characters printed into the output string (the size'th character then gets the terminating `\0'); if the return value is greater than or equal to the size argument, the string was too short and some of the printed characters were discarded. The output is always null-terminated.

MSVC: _snprintf returns the number of bytes stored in buffer, not counting the terminating null character. If the number of bytes required to store the data exceeds count, then count bytes of data are stored in buffer and a negative value is returned.
Back to top Go down
http://wcpforums.friendhood.net
 

Avoiding buffer overflows - strlcpy and strlcat - C++

View previous topic View next topic Back to top 
Page 1 of 1

Permissions in this forum:You cannot reply to topics in this forum
EverEffects Backup Forum :: C/C++/C#/VisualC++-
Jump to:  


   [Valid RSS]





Free forum | © phpBB | Free forum support | Contact | Report an abuse | Create a forum on Forumotion