警告 C6011: 取值的指標為 Null <name>
這則警告表示將取值 null 指標。如果指標值無效,則結果會是未定義的。
範例
下列程式碼會產生這則警告,因為如果沒有足夠的可用記憶體,則 malloc 呼叫可能會傳回 null:
#include <malloc.h>
void f( )
{
char *p = ( char * ) malloc( 10 );
*p = '\0';
// code ...
free( p );
}
若要更正這則警告,請檢查指標是否為 null 值,如下列程式碼所示:
#include <malloc.h>
void f( )
{
char *p = ( char * )malloc ( 10 );
if ( p )
{
*p = '\0';
// code ...
free( p );
}
}
在取值參數之前,您必須在 Pre 條件中使用 Null 屬性 (Property) 加註其參數的函式內,配置記憶體。下列程式碼會因為沒有先配置記憶體就嘗試在函式中取值 null 指標 (pc),而產生警告 C6011:
#include <sal.h>
using namespace vc_attributes;
void f([Pre(Null=Yes)] char* pc)
{
*pc='\0'; // warning C6011 - pc is null
// code ...
}
就記憶體遺漏和例外狀況而言, malloc 和 free 的使用上有很多缺點。若要避免這類遺漏和例外狀況的問題,請使用 C++ Standard Template Library (STL) 提供的機制。其中包括 shared_ptr、 unique_ptr和 vector。如需詳細資訊,請參閱智慧型指標 (現代 C++)與C++ 標準程式庫參考。