简体   繁体   中英

Runtime error when copying bytes from array

I'm trying to make a copy of an array. I know this is "bad code" but I'm getting it from a tutorial that makes heavy use of this and other low-level things. For some reason I'm getting a runtime error and I can't tell where it's coming from or why. Can anyone help? Thanks.

#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] << ' ';
}

The expression sizeof(b) returns the size of the array in bytes not the number of elements in the array. This causes the copy function to overwrite the stack frame resulting in a runtime error. Use sizeof(b[0]) instead to get the size of an individual element. If you want to retrieve the number of elements in an array you can use a combination of the two like so.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM