从阵列复制字节时出现运行时错误

时间:2013-05-22 01:24:43

标签: c++

我正在尝试复制一个数组。我知道这是“糟糕的代码”但我从一个大量使用这个和其他低级别的东西的教程中得到它。出于某种原因,我遇到了运行时错误,我无法分辨它的来源或原因。有人可以帮忙吗?感谢。

#include <iostream>

void copy_array(void *a, void const *b, std::size_t size, int amount)
{
    std::size_t bytes = size * amount;
    for (int i = 0; i < bytes; ++i)
        reinterpret_cast<char *>(a)[i] = static_cast<char const *>(b)[i];
}

int main()
{
    int a[10], b[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

    copy_array(a, b, sizeof(b), 10);

    for (int i = 0; i < 10; ++i)
        std::cout << a[i] << ' ';
}

1 个答案:

答案 0 :(得分:1)

表达式sizeof(b)以字节为单位返回数组的大小,而不是数组中元素的数量。这会导致复制功能覆盖堆栈帧,从而导致运行时错误。请使用sizeof(b[0])来获取单个元素的大小。如果要检索数组中元素的数量,可以使用两者的组合。

copy_array(a, b, sizeof(b[0]), sizeof(b) / sizeof(b[0]));