使用memcpy将int复制到char数组中,然后打印其成员:undefined behavior? [英] Using memcpy to copy an int into a char array and then printing its members: undefined behaviour?

查看:2656
本文介绍了使用memcpy将int复制到char数组中,然后打印其成员:undefined behavior?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下代码:

  int i = 1; 
char c [sizeof(i)];
memcpy(c,& i,sizeof(i));
cout<< static_cast< int>(c [0]);

请忽略这是否是好的代码。我知道输出取决于系统的字节序。这只是一个学术问题。



是这个代码:





  • 实施定义的行为

  • 定义良好的行为

  • 别的东西


解决方案

您要查找的规则是3.9p4:



< >

T 类型的对象的对象表示是 N <$类型 T 的对象占用的c $ c> unsigned char 对象,其中 N equals sizeof(T)。对象的值表示是
保存类型 T 的值的位集合。对于平凡可复制类型,值表示是对象表示中的一组位,其确定值,该值是实现定义的值集合的一个离散元素。


所以如果你使用 unsigned char ,你会得到实现定义的行为(任何一致的实现必须给你一个保证, )。

阅读 char 也是合法的,但是值未指定。然而,您保证使用不合格 char 将保留该值(因此bare char 不能有陷阱表示或填充位) ,根据3.9p2:


对于平凡可复制类型T的任何对象(基类子对象除外) object保存类型 T 的有效值,组成对象的底层字节(1.7)可以复制到 char unsigned char 。如果将 char unsigned char 数组的内容复制回对象,则对象将随后保持原始值。


(未指定值比实现定义值弱一些 - 语义是相同的,该平台不需要记录值是什么。)


Consider the following code:

int i = 1;
char c[sizeof (i)];
memcpy(c, &i, sizeof (i));
cout << static_cast<int>(c[0]);

Please ignore whether this is good code. I know the output depends on the endianness of the system. This is only an academic question.

Is this code:

  • Undefined behaviour
  • Implementation-defined behaviour
  • Well-defined behaviour
  • Something else

解决方案

The rule you are looking for is 3.9p4:

The object representation of an object of type T is the sequence of N unsigned char objects taken up by the object of type T, where N equals sizeof(T). The value representation of an object is the set of bits that hold the value of type T. For trivially copyable types, the value representation is a set of bits in the object representation that determines a value, which is one discrete element of an implementation-defined set of values.

So if you use unsigned char, you do get implementation-defined behavior (any conforming implementation must give you a guarantee on what that behavior is).

Reading through char is also legal, but then the values are unspecified. You are however guaranteed that using unqualified char will preserve the value (therefore bare char cannot have trap representations or padding bits), according to 3.9p2:

For any object (other than a base-class subobject) of trivially copyable type T, whether or not the object holds a valid value of type T, the underlying bytes (1.7) making up the object can be copied into an array of char or unsigned char. If the content of the array of char or unsigned char is copied back into the object, the object shall subsequently hold its original value.

("unspecified" values are a bit weaker than "implementation-defined" values -- the semantics are the same but the platform is not required to document what the values are.)

这篇关于使用memcpy将int复制到char数组中,然后打印其成员:undefined behavior?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆