一道C面試題引發的思考

char   *strA()
{
    char   str[]   =   "hello   word ";
    return   str;

       很明顯出錯了,返回指向局部變量的指針。
這個str裏存的地址   是函數strA棧楨裏 "hello       word   "的首地址
函數調用完成   棧楨恢復到調用strA之前的狀態
ebp   esp   被重置  
堆棧 "回縮 "
strA   棧楨不再屬於應該訪問的範圍
存於strA棧楨裏的 "hello       word   "當然也不應該訪問了

正確的寫法:

const char* strA()
{
   
char* str = "hello word";
   
return str;
}

char* strA()
{
   
static char str[] = "hello word";
   
return str;
}

char* strA()
{
   
char* str = new char[128];
    strcpy(str,
"hello word");
   
return str;

 

關於char* str = "hello word";

一般來講,修改這樣的串是不允許的(有的編譯器可以修改). "hello   word "在全局數據區

---------------  
                    Heap                   ¦  
---------------  
                    Stack                 ¦  
---------------  
                                Const     ¦(字符串常量通常放在data-const區中)  
        data--Common   ¦  
                                Data       ¦  
---------------  
                    Code                   ¦  
---------------  
既然是全局,那在strA之外自然也能訪問的拉,注意與在棧裏的串的區別

可以認爲這是C++語法上的一個歧義,不過也可以認爲是一種方便.
char   c[]   =   "hello   world ";
是分配一個局部數組.
char   *c   =   "hello   world ";
是分配一個全局數組.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章