How to properly memcpy without overflow issues

138 views Asked by At

In a legacy code I am getting buffer overflow errors in fortify audit.
Let me explain the issue here:
I have a function, say foo(size_t len, unsigned char **buf) ,in this foo I am memcopying a string variable in buf as follows.

char temp[256];

sprintf(temp, "abcd%s",somefunct_string.c_str()); //so the string temp is variable length

memcpy(*buf, temp, temp.length()); 

in practical, the temp.length() is always < len (which is buf alloted size). But fortify would give potential risk here.

how do i resolve this?

1

There are 1 answers

2
Lars On

Try calling the std::string::data() function to access the string via a pointer to the string.

memcpy(*buf, somefunct_string.data(), somefunct_string.size());

Also, memcpy_s() is available since C11.

memcpy_s(*buf, temp.length(), somefunct_string.data(), somefunct_string.size())

memcpy() and memcpy_s() are called when copying a sequence from one array to another array. If the copy overlaps within the same array, memmove() or memmove_s() should be called.