Making your C++ code robust

  • Cleaning Up Released Handles 

      在释放一个句柄以前,务必将这个句柄复制伪NULL (0或则其余默认值)。这样可以保证程序其余地方不会重复使用无效句柄。看看以下代码,如何清除一个Windows API的文件句柄:数组

HANDLE hFile = INVALID_HANDLE_VALUE; 
  
  // Open file
  hFile = CreateFile(_T("example.dat"), FILE_READ|FILE_WRITE, FILE_OPEN_EXISTING);
  if(hFile==INVALID_HANDLE_VALUE)
  {
    return FALSE; // Error opening file
  }
 
  // Do something with file
 
  // Finally, close the handle
  if(hFile!=INVALID_HANDLE_VALUE)
  {
    CloseHandle(hFile);   // Close handle to file
    hFile = INVALID_HANDLE_VALUE;   // Clean up handle
  }

下面代码展现如何清除File *句柄:

// First init file handle pointer with NULL
  FILE* f = NULL;
 
  // Open handle to file
  errno_t err = _tfopen_s(_T("example.dat"), _T("rb"));
  if(err!=0 || f==NULL)
    return FALSE; // Error opening file
 
  // Do something with file
 
  // When finished, close the handle
  if(f!=NULL) // Check that handle is valid
  {
    fclose(f);
    f = NULL; // Clean up pointer to handle
  }

  • Using delete [] Operator for Arrays 

     若是你分配一个单独的对象,能够直接使用new ,一样你释放单个对象的时候,能够直接使用delete . 然而,申请一个对象数组对象的时候可使用new,可是释放的时候就不能使用delete ,而必须使用delete[]:ide

// Create an array of objects
 CVehicle* paVehicles = new CVehicle[10];
 delete [] paVehicles; // Free pointer to array
 paVehicles = NULL; // Set pointer with NULL
or
 // Create a buffer of bytes
 LPBYTE pBuffer = new BYTE[255];
 delete [] pBuffer; // Free pointer to array
 pBuffer = NULL; // Set pointer with NULL

  • Allocating Memory Carefully 

     有时候,程序须要动态分配一段缓冲区,这个缓冲区是在程序运行的时候决定的。例如、你须要读取一个文件的内容,那么你就须要申请该文件大小的缓冲区来保存该文件的内容。在申请这段内存以前,请注意,malloc() or new是不能申请0字节的内存,如否则,将致使malloc() or new函数调用失败。传递错误的参数给malloc() 函数将致使C运行时错误。以下代码展现如何动态申请内存:函数

// Determine what buffer to allocate.
  UINT uBufferSize = GetBufferSize(); 
 
  LPBYTE* pBuffer = NULL; // Init pointer to buffer
 
  // Allocate a buffer only if buffer size > 0
  if(uBufferSize>0)
   pBuffer = new BYTE[uBufferSize];

 为了进一步了解如何正确的分配内存,你能够读下Secure Coding Best Practices for Memory Allocation in C and C++这篇文章。post

  • Using Asserts Carefully

       Asserts用语调试模式检测先决条件和后置条件。但当咱们编译器处于release模式的时候,Asserts在预编阶段被移除。所以,用Asserts是不可以检测咱们的程序状态,错误代码以下:spa

#include <assert.h>
  
  // This function reads a sports car's model from a file
  CVehicle* ReadVehicleModelFromFile(LPCTSTR szFileName)
  {
    CVehicle* pVehicle = NULL; // Pointer to vehicle object
 
    // Check preconditions
    assert(szFileName!=NULL); // This will be removed by preprocessor in Release mode!
    assert(_tcslen(szFileName)!=0); // This will be removed in Release mode!
 
    // Open the file
    FILE* f = _tfopen(szFileName, _T("rt"));
 
    // Create new CVehicle object
    pVehicle = new CVehicle();
 
    // Read vehicle model from file
 
    // Check postcondition 
    assert(pVehicle->GetWheelCount()==4); // This will be removed in Release mode!
 
    // Return pointer to the vehicle object
    return pVehicle;
  }

  看看上述的代码,Asserts可以在debug模式下检测咱们的程序,在release 模式下却不能。因此咱们仍是不得不用if()来这步检测操做。正确的代码以下;

CVehicle* ReadVehicleModelFromFile(LPCTSTR szFileName, )
  {
    CVehicle* pVehicle = NULL; // Pointer to vehicle object
 
    // Check preconditions
    assert(szFileName!=NULL); // This will be removed by preprocessor in Release mode!
    assert(_tcslen(szFileName)!=0); // This will be removed in Release mode!
 
    if(szFileName==NULL || _tcslen(szFileName)==0)
      return NULL; // Invalid input parameter
 
    // Open the file
    FILE* f = _tfopen(szFileName, _T("rt"));
 
    // Create new CVehicle object
    pVehicle = new CVehicle();
 
    // Read vehicle model from file
 
    // Check postcondition 
    assert(pVehicle->GetWheelCount()==4); // This will be removed in Release mode!
 
    if(pVehicle->GetWheelCount()!=4)
    { 
      // Oops... an invalid wheel count was encountered!  
      delete pVehicle; 
      pVehicle = NULL;
    }
 
    // Return pointer to the vehicle object
    return pVehicle;
  }

  • Checking Return Code of a Function 

        判定一个函数执行必定成功是一种常见的错误。当你调用一个函数的时候,建议检查下返回代码和返回参数的值。以下代码持续调用Windows API ,程序是否继续执行下去依赖于该函数的返回结果和返回参数值。debug

HRESULT hres = E_FAIL;
    IWbemServices *pSvc = NULL;
    IWbemLocator *pLoc = NULL;
    
    hres =  CoInitializeSecurity(
        NULL, 
        -1,                          // COM authentication
        NULL,                        // Authentication services
        NULL,                        // Reserved
        RPC_C_AUTHN_LEVEL_DEFAULT,   // Default authentication 
        RPC_C_IMP_LEVEL_IMPERSONATE, // Default Impersonation  
        NULL,                        // Authentication info
        EOAC_NONE,                   // Additional capabilities 
        NULL                         // Reserved
        );
                      
    if (FAILED(hres))
    {
        // Failed to initialize security
        if(hres!=RPC_E_TOO_LATE) 
           return FALSE;
    }
    
    hres = CoCreateInstance(
        CLSID_WbemLocator,             
        0, 
        CLSCTX_INPROC_SERVER, 
        IID_IWbemLocator, (LPVOID *) &pLoc);
    if (FAILED(hres) || !pLoc)
    {
        // Failed to create IWbemLocator object. 
        return FALSE;               
    }
   
    hres = pLoc->ConnectServer(
         _bstr_t(L"ROOT\\CIMV2"), // Object path of WMI namespace
         NULL,                    // User name. NULL = current user
         NULL,                    // User password. NULL = current
         0,                       // Locale. NULL indicates current
         NULL,                    // Security flags.
         0,                       // Authority (e.g. Kerberos)
         0,                       // Context object 
         &pSvc                    // pointer to IWbemServices proxy
         );
    
    if (FAILED(hres) || !pSvc)
    {
        // Couldn't conect server
        if(pLoc) pLoc->Release();     
        return FALSE;  
    }
    hres = CoSetProxyBlanket(
       pSvc,                        // Indicates the proxy to set
       RPC_C_AUTHN_WINNT,           // RPC_C_AUTHN_xxx
       RPC_C_AUTHZ_NONE,            // RPC_C_AUTHZ_xxx
       NULL,                        // Server principal name 
       RPC_C_AUTHN_LEVEL_CALL,      // RPC_C_AUTHN_LEVEL_xxx 
       RPC_C_IMP_LEVEL_IMPERSONATE, // RPC_C_IMP_LEVEL_xxx
       NULL,                        // client identity
       EOAC_NONE                    // proxy capabilities 
    );
    if (FAILED(hres))
    {
        // Could not set proxy blanket.
        if(pSvc) pSvc->Release();
        if(pLoc) pLoc->Release();     
        return FALSE;               
    }
相关文章
相关标签/搜索