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?
Try calling the std::string::data() function to access the string via a pointer to the string.
Also, memcpy_s() is available since C11.
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.