简体   繁体   English

大小如何搭配memcpy使用?

[英]How does size work with memcpy?

My question relates to how safe the following code is: 我的问题与以下代码的安全性有关:

#define ARRAY_SIZE 10

std::array<BYTE, ARRAY_SIZE> myArray;
char* string = "this_sentence_is_longer_than_10_bytes"

memcpy(&myArray, string, ARRAY_SIZE);

Result: myArray is filled [0-9] with "this_sente" 结果:myArray用"this_sente"填充[0-9]

In terms of it being safe, I need to know what is happening to the rest of 'string'. 就安全而言,我需要知道其余“字符串”发生了什么。 Is it being ignored completely due to the size given or is it being thrown off the end of the array? 它是由于给定的大小而被完全忽略还是被丢弃在数组的末尾?

edit: I now have 编辑:我现在有

#define ARRAY_SIZE 10

std::array<BYTE, ARRAY_SIZE> myArray;
char* string = "this_sentence_is_longer_than_10_bytes"

if (strlen(string) < ARRAY_SIZE)
{
    BYTE clearArray[ARRAY_SIZE] = {0};
    memcpy(&myArray, clearArray, ARRAY_SIZE);
    memcpy(&myArray, string, strlen(string));
}
else
{
    memcpy(&myArray, string, ARRAY_SIZE);
}

It now pads out the std:array with zeroes if the string is shorter than 10 characters, otherwise it uses the initial method. 现在,如果字符串短于10个字符,它将用零填充std:array,否则它将使用初始方法。

The rest of the string constant gets ignored, as if it's not there. 字符串常量的其余部分将被忽略,好像不存在。 memcpy stops as soon as it reaches size bytes. memcpy在达到size字节后立即停止。

Note that although it is safe to pass a memory block that is larger than size to memcpy , passing a block that is shorter triggers undefined behavior. 请注意,尽管将大于size的内存块传递给memcpy是安全的,但传递较短的块会触发未定义的行为。 For example, if you pass string that has fewer than nine characters, memcpy will copy invalid characters past the end of the string into myArray . 例如,如果传递的string少于9个字符,则memcpy会将字符串末尾的无效字符复制到myArray

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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