2014-01-16 32 views
4

我正在測試對齊方式,並確定iOS模擬器有些奇怪(XCode 4.3.2和XCode 4.5)。iOS模擬器內存​​對齊

在iOS模擬器上,即使使用屬性((aligned(4)))來強制4字節邊界,結構也會與8字節邊界對齊。檢查是否在末尾填充了0x00000001以對齊8字節的邊界。

如果myStruct變量在全局範圍中定義,那麼模擬器會將其與4字節邊界對齊,因此它可能與堆棧有關。

模擬器是i386所以它的32位,它必須對齊到4字節的邊界。那麼,這是什麼原因,爲什麼它對齊到64位邊界?它是一個功能還是一個錯誤?

(我知道這是沒有必要用模擬器作鬥爭,但它可能會導致扎進微妙的問題。)

typedef struct myStruct 
{ 
    int a; 
    int b; 
} myStruct; 
//} __attribute__ ((aligned (4))) myStruct; 

-(void)alignmentTest 
{ 
    // Offset 16*n (0x2fdfe2f0) 
    int __attribute__ ((aligned (16))) force16ByteBoundary = 0x01020304; 

    // Offset 16*n-4 (0x2fdfe2ec) 
    int some4Byte = 0x09080706; 

    // Offset 16*n-12 (0x2fdfe2e4) 
    myStruct mys; 

    mys.a = 0xa1b1c1d1; 
    mys.b = 0xf2e28292; 

    NSLog(@"&force16ByteBoundary: %p/&some4Byte: %p/&mys: %p", 
     &force16ByteBoundary, &some4Byte, &mys); 
} 

編輯優化關閉,-O0)

  • 模擬器(iOS 5.1)結果;

    (LLDB)×` & MYS ` -fx

    0xbfffda60:0xa1b1c1d1 0xf2e28292 0x09080706

    0xbfffda70:0x01020304

    & force16ByteBoundary:0xbfffd A70/& some4Byte:0xbfffda6c/& MYS: 0xbfffda60

  • 設備(iOS 5中。1)結果;

    (LLDB)×` & MYS ` -fx

    0x2fdfe2e4:0xa1b1c1d1 0xf2e28292 0x09080706 0x01020304

    & force16ByteBoundary:0x2fdfe2f0/& some4Byte:0x2fdfe2ec/& MYS: 0x2fdfe2e4

新調查結果

- On Simulator and Device; 
    - Building for Release or Debug does not make any difference for alignments. 
    - Local or global variables of "long long", double types are aligned to 8 byte boundary although they must be aligned to 4 byte boundary. 
    - There is no problem with global variables of structs. 
- On Simulator; 
    - Local variables of structs are aligned to 8 byte boundary even when there is only a char member in the struct. 

編輯

我只能找出 「數據類型和數據對齊」 爲iOS here。 (另外,它們可以從ILP32 alignments here.推斷出)

+2

模擬器是英特爾,iDevice是ARM ...不同的架構...... ARM的字節對齊方式更具限制性,英特爾更寬容。 –

+0

您正在運行模擬器的設備是64位? –

+0

調試和發佈版本的結果是否相同? –

回答

0

通常,對齊屬性隻影響結構內項目的相對對齊。這允許向後兼容想要直接從網絡或二進制文件中將數據大容量複製到結構中的代碼。

對齊屬性不會影響堆棧中分配的局部變量的對齊。無法保證堆疊物品的排列和對齊,並且通常會針對設備的每個物品進行最佳對齊。因此,如果一個基於386的設備可以通過8字節對齊的方式在一次操作中從內存中獲取一個64位長的內存,它就會這樣做。如果數據未完全對齊,某些處理器實際上會損失大量性能。某些處理器可能會嘗試讀取未正確對齊的數據時發生異常。