Improve memory safety in the DOS Drive Cache class
- Fix Bitu printf format type - Check a pointer prior to dereferencing it - Prevent writing one-beyond the last index - Replace strcpy with with helper safe_strcpy, provided by @dreamer - thank you! - Replace strcat with strncat - Add constructor intializers for scalars and arrays - Initialize and replace 0-value pointers with nullptr - Pass in the buffer length when strncpy'ing into a function variable
This commit is contained in:
parent
88cdd8d3a0
commit
cff6b05559
4 changed files with 200 additions and 115 deletions
|
@ -21,9 +21,10 @@
|
|||
#define DOSBOX_SUPPORT_H
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstdio>
|
||||
#include <ctype.h>
|
||||
#include <string.h>
|
||||
#include <string>
|
||||
#include <ctype.h>
|
||||
#ifndef DOSBOX_DOSBOX_H
|
||||
#include "dosbox.h"
|
||||
#endif
|
||||
|
@ -33,6 +34,27 @@
|
|||
#define strncasecmp(a,b,n) _strnicmp(a,b,n)
|
||||
#endif
|
||||
|
||||
/// Copy a string into C array
|
||||
///
|
||||
/// This function copies string pointed by src to fixed-size buffer dst.
|
||||
/// At most N bytes from src are copied, where N is size of dst.
|
||||
/// If exactly N bytes are copied, then terminating null byte is put
|
||||
/// into buffer, thus buffer overrun is prevented.
|
||||
///
|
||||
/// Function returns pointer to buffer to be compatible with std::strcpy.
|
||||
///
|
||||
/// Usage:
|
||||
///
|
||||
/// char buffer[2];
|
||||
/// safe_strcpy(buffer, "abc");
|
||||
/// // buffer is filled with "a"
|
||||
|
||||
template<size_t N>
|
||||
char * safe_strcpy(char (& dst)[N], const char * src) noexcept {
|
||||
snprintf(dst, N, "%s", src);
|
||||
return & dst[0];
|
||||
}
|
||||
|
||||
#define safe_strncpy(a,b,n) do { strncpy((a),(b),(n)-1); (a)[(n)-1] = 0; } while (0)
|
||||
|
||||
#ifdef HAVE_STRINGS_H
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue