參考Is using memcmp on array of int strictly conforming?
以下代碼一定會輸出ok嗎?
#include <stdio.h>
#include <string.h>
struct S { int array[2]; };
int main () {
struct S a = { { 1, 2 } };
struct S b;
b = a;
if (memcmp(b.array, a.array, sizeof(b.array)) == 0) {
puts("ok");
}
return 0;
}
我在vs2005以及gcc4.4.3上做了測試,都輸出了ok。但這并不意味這個代碼會永遠輸出ok。問題主要集中于這里使用了賦值語句來復制值,但卻使用了memcmp這個基于內(nèi)存數(shù)據(jù)比較的函數(shù)來比較值。
c語言中的賦值運算符(=)被定義為基于值的復制,而不是基于內(nèi)存內(nèi)容的復制。
C99 section 6.5.16.1 p2: In simple assignment (=), the value of the right operand is converted to the type of the assignment expression and replaces the value stored in the object designated by the left operand.
這個其實很好理解,尤其在不同類型的數(shù)字類型間復制時,例如:
float a = 1.1;
int b = a;
因為浮點數(shù)和整形數(shù)的內(nèi)存布局不一樣,所以肯定是基于值的一種復制。另外,按照語言標準的思路來看,內(nèi)存布局這種東西一般都屬于實現(xiàn)相關(guān)的,所以語言標準是不會依賴實現(xiàn)去定義語言的。
上面的定理同樣用于復雜數(shù)據(jù)類型,例如結(jié)構(gòu)體。我們都知道結(jié)構(gòu)體每個成員之間可能會有字節(jié)補齊,而使用賦值運算符來復制時,會不會復制這些補齊字節(jié)的內(nèi)容,是語言標準未規(guī)定的。這意味著使用memcmp比較兩個通過賦值運算符復制的兩個結(jié)構(gòu)體時,其結(jié)果是未定的。
但是上面的代碼例子中,比較的其實是兩個int數(shù)組。這也無法確認結(jié)果嗎?這個問題最終集中于,難道int也會有不確定的補齊字節(jié)數(shù)據(jù)?
C99 6.2.6.2 integer types For signed integer types, the bits of the object representation shall be divided into three groups: value bits, padding bits, and the sign bit. […] The values of any padding bits are unspecified.
這話其實我也不太懂。一個有符號整數(shù)int,其內(nèi)也有補齊二進制位(bits)?
但無論如何,這個例子都不算嚴謹?shù)拇a。人們的建議是使用memcpy來復制這種數(shù)據(jù),因為memcpy和memcmp都是基于內(nèi)存內(nèi)容來工作的。