【发布时间】:2021-02-25 00:30:28
【问题描述】:
我在网上读到memmove 如果要复制的字节数为 0,则预计不会执行任何操作。但是我想知道的是,是否预计不会读取源和目标指针案例
下面是我的部分代码的简化版,我感兴趣的部分是shiftLeft:
#include <array>
#include <cstring>
#include <iostream>
class Foo final {
unsigned just = 0;
unsigned some = 0;
unsigned primitives = 0;
};
template <unsigned Len>
class Bar final {
unsigned depth = 0;
std::array<Foo, Len> arr;
public:
Bar() = default;
// Just an example
void addFoo() {
arr[depth] = Foo();
depth++;
}
void shiftLeft(unsigned index) {
// This is what my question focuses on
// If depth is 10 and index is 9 then index + 1 is out of bounds
// However depth - index - 1 would be 0 then
std::memmove(
&arr[index],
&arr[index + 1],
(depth - index - 1) * sizeof(Foo)
);
depth--;
}
};
int main() {
Bar<10> bar;
for (unsigned i = 0; i < 10; ++i)
bar.addFoo();
bar.shiftLeft(9);
return 0;
}
当Len 是10,depth 是10,并且index 是9 时,index + 1 会读出越界。然而,在这种情况下,depth - index - 1 也是0,这意味着memmove 不会执行任何操作。这段代码安全吗?
【问题讨论】:
-
即使它是安全的(正如@paxdiablo 在他的回答中解释的那样),它也不正确:不会移动任何内容,但会减少
depth。 -
@VladFeinstein,不,它是正确的。当最后一个元素被删除时,不需要移动任何东西(没有
memmove)但元素的数量需要减少(depth--)