簡體   English   中英

函數中傳遞值變量和局部變量的變量是否不會連續分配?

[英]Are variables for pass by value variables and local variables in a function not allocated continuously?

我想知道變量在堆棧上的分配方式,所以我制作了一個小型測試程序

#include <iostream>
#include <stdlib.h>
using namespace std;

class test
{
public:
    test()
    {

    }
    test(const test &obj)
    {
        cout << "a clone of test has been created" << endl;
    }
};

void foo(test variable_01, test variable_02)
{
    cout << "v3 and v4 have not been created" << endl;
    char variable_03;
    char variable_04;
    cout << "v3 and v4 have been created" << endl;

    cout << "Adrress of variable 01: " << static_cast<void*>(&variable_01) << endl;
    cout << "Adrress of variable 02: " << static_cast<void*>(&variable_02) << endl;
    cout << "Adrress of variable 03: " << static_cast<void*>(&variable_03) << endl;
    cout << "Adrress of variable 04: " << static_cast<void*>(&variable_04) << endl;
}


int main()
{
    test temp;
    foo(temp,temp);
    return 0;
}

這是結果

a clone of test has been created
a clone of test has been created
v3 and v4 have not been created
v3 and v4 have been created
Adrress of variable 01: 0xbf9dd3ae
Adrress of variable 02: 0xbf9dd3af
Adrress of variable 03: 0xbf9dd37e
Adrress of variable 04: 0xbf9dd37f

我們這里有兩組變量

  • 按值傳遞變量的副本:v_01和v_02(G1)
  • 局部變量:v_03和v_04(G2)

根據結果​​,我們知道G1已分配在G2之前(也許是v_01-> v_02-> v_03-> v_04)。 但是有一些奇怪的事情:

  • 每個組中的每個變量都是連續分配的,但是G1和G2似乎彼此距離有點遠,我認為它們應該都是0xbf9dd3a_或0xbf9dd37_或{0xbf9dd3ae-> 0xbf9dd3b1}或{0xbf9dd37e-> 0xbf9dd381}
  • G1的地址始終是G2的較大地址。 我可以基於堆棧的工作方式和程序在加載時的數據段對此進行解釋。 這是已加載程序的數據段的快捷方式(來源: http : //www.inf.udec.cl/~leo/teoX.pdf )。

在此處輸入圖片說明

  • 但是,如果上面的解釋是正確的,我將無法解釋為什么在每個組中,變量的地址都基於它們的創建時間。 (例如:v_03在v_04之前,因此v_04的地址大於v_03的地址)

盡管在G2之前創建了地址,但為什么G1的地址大於G2?

為什么每個組中的變量都是連續分配的,但是這些組之間的距離有點遠?

為什么組中變量的地址與這些組之間的地址順序相比具有不同的順序?

在C語言中(不確定C ++,但我懷疑它是相似的),獨立對象的地址之間沒有關系。 該語言甚至沒有定義它們之間的順序關系。 ><<=>=運算符在未指向同一數組的指針上使用時具有未定義的行為。

至於為什么對象最終在指向它們的指針的數字地址之間具有特定的關系,這純粹是編譯器實現細節的結果,它取決於特定的編譯器,編譯器版本和使用的選項。

它依賴於編譯器,而不是標准的一部分。 編譯器決定數據將需要多少內存,為該數據保留內存塊,並決定如何分配它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM