[C++]理解指標—轉載

來源:互聯網
上載者:User

1  What will happen after running the "Test"?

#include <iostream.h>

void GetMemory(char *p, int num)
{
    p = (char *)malloc(sizeof(char) *
 num);
}

int main()
{
    char *str =
 NULL;

    GetMemory(str, 100);
    strcpy(str, "hello"
);

    return 0;
}

分析:由於void GetMemory(char *p, int num)中的*p實際上是主函數中的一個str的一個副本,編譯器總是要為函數的每個參數製作臨時副本。在本倒中,p申請了新的記憶體,只是把p把指的記憶體位址改變了,但str絲毫未變。因為GetMemory沒有傳回值,因此str並不指向p所申請的那段記憶體,所以函數GetMemory並不能輸出任何東西。事實上,每執行一次GetMemory就會申請一塊記憶體,但申請的記憶體卻不能有效釋放,結果是記憶體一直被獨佔,最終造成記憶體泄露。

答案:程式崩潰。因為GetMemory並不能傳遞動態記憶體,Test函數中的str一直都是NULL。

//---------------------------------------------------------------------------------------------------

以下是正常的申請方式:

 

方法一:用指標參數去申請記憶體時,應用採用指向指標的指標,把str的地址傳給函數GetMemory

 

#include <iostream.h>

void GetMemory(char **p, int num)
{
    *p = (char *)malloc(sizeof(char) *
 num);
}

int main()
{
    char *str =
 NULL;

    GetMemory(&str, 100);
    strcpy(str, "hello"
);

    std::cout << *str << std::endl;
    std::cout << str <<
 std::endl;
    std::cout << &str <<
 std::endl;

    return 0;
}

 

方法二:函數傳回值為指標類型來傳遞動態記憶體

 

#include <iostream>

char *GetMemory(char *p, int num)
{
    return p = (char *)malloc(sizeof(char) *
 num);
}

int main()
{
    char *str =
 NULL;

    str = GetMemory(str, 100);
    strcpy(str, "hello"
);

    std::cout << *str << std::endl;
    std::cout << str <<
 std::endl;
    std::cout << &str <<
 std::endl;

    return 0;
}

  //------------------------------------------------------------------------------------------------

 

 What will happen after running the "Test"?


#include <iostream>

char *GetMemory(void)
{
    char p[] = "hello world"
;
    return
 p;
}

int main()
{
    char *str =
 NULL;
    str =
 GetMemory();
    std::cout << str <<
 std::endl;

    return 0;
}

答案:可能是亂碼,也有可能是正常輸出。因為GetMemory返回的是指向“棧記憶體”的指標,該指標的地址不是NULL,但其原來的內容已經被清除,新內容不可知。

 //------------------------------------------------------------------------------------------------

【記憶體操作及問題相關知識點】為了能徹底解決動態記憶體傳遞的問題,我們回顧一下記憶體管理的知識要點.
記憶體配置方式有三種:

從靜態儲存地區分配。記憶體在程式編譯的時候就已經分配好,這塊記憶體在程式的整個運行期間都存在。例如全域變數,static變數。

 

從堆上分配,亦稱動態記憶體分配。程式在啟動並執行時候用malloc或new申請任意多少的記憶體,程式員自己負責在何時用free或delete釋放記憶體。動態記憶體的生存期由我們決定,使用非常靈活。

在棧上建立。在執行函數時,函數內局部變數的儲存單元都可以在棧上建立,函數執行結束時這些儲存單元自動被釋放。棧記憶體配置運算內建於處理器的指令集中,效率很高,但是分配的記憶體容量有限。

 

原網址:http://blog.csdn.net/seuzyq/archive/2009/10/06/4636849.aspx

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.