2017-02-13 82 views
0

直到我加入static,下面的C++函數還沒有在Visual Studio 6(1998年)中工作。爲什麼?visual C++ VC6靜態

char* test(char* s1) 

{ 

    static char s[100]; strcpy(s, s1); char* r = s1; 


     if(s[0] == '\n') 
     { 
     s[0] = ' '; 
     cout << "\n"; 
     } 

     return r; 

} 
+0

cout <<「\ n」後:應該是r = s; –

回答

2

將指針返回棧變量是危險的不安全(未定義行爲)。這包括在堆棧上分配的數組。一旦函數返回,堆棧變量佔用的內存基本上就會被釋放。

char* test(char* s1) 
{ 
    char s[100]; 
    ... 
    return s; // Bad! s is invalid memory when the function returns 
} 

通過將數組分配靜態的,它的分配將持續存在,更安全......

char* test(char* s1) 
{ 
    static char s[100]; 
    ... 
    return s; 
} 

但是,如果任何代碼路徑緩存從「測試」返回的指針,調用另一個代碼路徑此功能可能會使先前的結果無效。

對於您的示例,您可能希望在返回之前複製該字符串。期望以後調用者將「釋放」內存:

char* test(char* s1) 
{ 
    char* s = strdup(s1); 
    strcpy(s, s1); 
    if(s[0] == '\n') 
    { 
     s[0] = ' '; 
     cout << "\n"; 
    } 
    return s; // caller is expected to "free" the memory allocation later 
} 
+0

是的,這是古老的,但它只是古代的VC6。你仍然可以返回一個'std :: string',這會更安全。 VC6大部分都是正確的。 – MSalters