相关疑难解决方法(0)

memcpy()vs memmove()

我想了解的区别memcpy()memmove(),和我读的文本memcpy(),而没有照顾重叠源和目的地memmove()一样.

但是,当我在重叠的内存块上执行这两个函数时,它们都会给出相同的结果.例如,在memmove()帮助页面上采用以下MSDN示例: -

有没有更好的例子来理解它的缺点memcpymemmove解决方法?

// crt_memcpy.c
// Illustrate overlapping copy: memmove always handles it correctly; memcpy may handle
// it correctly.

#include <memory.h>
#include <string.h>
#include <stdio.h>

char str1[7] = "aabbcc";

int main( void )
{
    printf( "The string: %s\n", str1 );
    memcpy( str1 + 2, str1, 4 );
    printf( "New string: %s\n", str1 );

    strcpy_s( str1, sizeof(str1), "aabbcc" );   // reset string

    printf( "The string: …
Run Code Online (Sandbox Code Playgroud)

c memcpy memmove

151
推荐指数
6
解决办法
14万
查看次数

`string.assign(string.data(), 5)` 是定义明确的还是 UB?

一个同事想写这个:

std::string_view strip_whitespace(std::string_view sv);

std::string line = "hello  ";
line = strip_whitespace(line);
Run Code Online (Sandbox Code Playgroud)

我说返回string_view让我先验地感到不安,而且,这里的别名对我来说看起来像 UB。

我可以肯定地说,line = strip_whitespace(line)在这种情况下相当于line = std::string_view(line.data(), 5). 我相信会调用string::operator=(const T&) [with T=string_view],其定义为等价于line.assign(const T&) [with T=string_view],其定义为等价于line.assign(line.data(), 5),其定义为:

Preconditions: [s, s + n) is a valid range.
Effects: Replaces the string controlled by *this with a copy of the range [s, s + n).
Returns: *this.
Run Code Online (Sandbox Code Playgroud)

但这并没有说明出现混叠时会发生什么。

我昨天在 cpplang Slack 上问了这个问题,得到的答案喜忧参半。在这里寻找超级权威的答案,和/或对真实图书馆供应商实施的实证分析。


我写测试用例string::assignvector::assign …

c++ stl undefined-behavior

11
推荐指数
1
解决办法
213
查看次数

标签 统计

c ×1

c++ ×1

memcpy ×1

memmove ×1

stl ×1

undefined-behavior ×1