簡體   English   中英

Visual C ++ VC6靜態

[英]visual c++ VC6 static

在我添加static之前,以下C ++函數無法在Visual Studio 6(1998年)中使用。 為什么?

char* test(char* s1)

{

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


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

      return r;

}

將指針返回到堆棧變量很危險(不確定的行為)。 這包括在堆棧上分配的數組。 函數返回后,堆棧變量所占用的內存實際上就被釋放了。

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;
}

但是,如果任何代碼路徑都緩存了從“ test”返回的指針,則另一個調用此函數的代碼路徑可能會使先前的結果無效。

對於您的示例,您可能要在返回之前復制字符串。 期望調用者稍后會“釋放”內存:

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
}

暫無
暫無

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

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