Welcome to our Secure Development Tips blog

Every other week, we provide expert tech tips on how to build and deploy secure applications.  These best practices, derived from Security Innovation’s assessments of the worlds’ most dominant software applications,  are taken directly from our TeamMentor product, which includes more than 3,500 guidance assets and articles on secure software design, coding and testing.    

Recent Security Innovation Blog Post:

Subscribe by Email

Your email:

Secure Development Tips

a blog with tips relating to secure application development, from Security Innovation's eknowledge database, TeamMentor

Current Articles | RSS Feed RSS Feed

Allocate Enough Buffer Space for Copying Data


What to Do

Only copy the amount of data that can fit in the array or string. Make sure that the array or string is large enough to fit all the data, including the possible trailing null.


Copying more data than an array or string can fit results in a buffer overflow.


Allocate enough buffer space for copying data, when data is being copied to an array or a string.


Perform the following steps to assure that your code allocates enough buffer space when copying data to prevent buffer overflows:

  1. Identify all functions that copy data to strings or arrays. List the components, modules, and libraries that do the most amount of data handling. Usually there exists some code heavy on manipulating data that copies many buffers or constructs various strings.
  2. Calculate the amount of memory that is used by data being copied or set a maximum size limit for valid data. Make sure to include a trailing null if a null-terminated string is being copied. When calculating the size of data, count the amount of memory it uses, not the amount of elements in the array. Be careful when using the sizeof() function, because it returns the size of a pointer when an array containing data is passed as a parameter to the function. The memory size of data should be calculated beforehand, ideally in the same scope in which the data structure containing data is declared, and passed as an argument to the function that does the copying.
  3. Allocate memory for the buffer. Once the amount of memory needed to fit all the data is determined, allocate an array or a string of a sufficient size. Write code to handle possible memory allocation errors.
  4. Check bounds when copying. Use the size of the allocated array or string when copying to assure that only the amount of data that fits into the array is copied. This should always be the case if the amount of memory to allocate is calculated correctly, but for extra security it is a good idea to write code in a way that truncates data if it doesn't fit into the buffer.

Additional Resources


Currently, there are no comments. Be the first to post one!
Post Comment
Website (optional)

Allowed tags: <a> link, <b> bold, <i> italics