我已经用 C++ 实现了基本的 memset/memcpy/strcpy 实现,效果很好。但是,如果我要执行以下操作,是否有检测缓冲区溢出的方法:
例子:
int main()
{
char *buf = (char *)calloc(10, sizeof(char));
__strcpy(buf, "Hello World");
// buffer size: 10, copy size: 12 (including '\0') - overflow
}
实现(typedef unsigned int UINT
):
void *__memset(void *_Dst, int _Val, UINT _Size)
{
UINT *buf = (UINT *)_Dst;
while (_Size--)
{
*buf++ = (UINT)_Val;
}
return _Dst;
}
void *__memcpy(void *_Dst, const void *_Src, UINT _Size)
{
UINT *buf = (UINT *)_Dst;
UINT *src = (UINT *)_Src;
while (_Size--)
{
*buf++ = *src++;
}
return _Dst;
}
char *__strcpy(char *_Dst, const char *_Src)
{
while ((*_Dst++ = *_Src++) != '\0');
return _Dst;
}
最佳答案
在您的程序中无法检测到缓冲区溢出。操作系统正在检测它们。您只能检查代码中的潜在陷阱(if/else、断言、异常)。或者你使用像 valgrind 这样的分析工具。
关于C++ memset/memcpy/strcpy 实现 - 检查缓冲区溢出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21908859/