C++ memset/memcpy/strcpy 实现 - 检查缓冲区溢出

标签 c++

我已经用 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/

相关文章:

c++ - 如何防止手动实例化所有模板类型?

c++ - 在xml中获取子节点的名称将返回#text C++

c++ - "missing template argument"是什么意思?

c++ - 使用大括号/括号将值赋给 std::string

c++ - 至少一个字符的正则表达式

c++ - 如何在一个函数中访问另一个函数中的变量?

c++ - 基于 C++ 中的另一个变量类型派生变量类型

c++ - 如何捕捉MessageWebSocket的ConnectAsync方法抛出的异常?

c++ - 既然 C++ 知道类型,它能推断出点和箭头吗?

c++ - 如何使用 boost::call_once 在 Linux 上用 C++ 设计单例类?