自由分配的内存生成异常 - C++

Jim*_*ell 1 c++ malloc free exception visual-studio-2008

我的应用程序中有一个函数,其中分配内存以格式化端口名称. CreateFile被叫打开港口.在函数结束时free调用以尝试释放分配的内存.

DWORD CSerialPort::Open( wchar_t * port )
{
    DCB dcb = {0};
    LPTHREAD_START_ROUTINE pThreadStart;
    void * pvThreadData = NULL;
    wchar_t * pwcPortName = NULL;
    DWORD dwRetVal = ERROR_SUCCESS;

    /* Validate parameters. */

    pwcPortName = (wchar_t *)malloc( wcslen( port ) + 6 );

    if ( pwcPortName == NULL )
    {
        TRACE(_T("CSerialPort::Open : Failed to allocate memory for formatted serial port name.\r\n\tError: %d\r\n\tFile: %s\r\n\tLine: %d\r\n"), ERROR_NOT_ENOUGH_MEMORY, __WFILE__, __LINE__);
        return ERROR_NOT_ENOUGH_MEMORY;
    }

    memcpy( pwcPortName, L"\\\\.\\", 4 * 2 );
    memcpy( pwcPortName + 4, port, wcslen( port ) * 2 + 2 );

    // Get a handle to the serial port.
    _hSerialPort = CreateFile(
        pwcPortName,                    // Formatted serial port
        GENERIC_READ | GENERIC_WRITE,   // Access: Read and write
        0,                              // Share: No sharing
        NULL,                           // Security: None
        OPEN_EXISTING,                  // OM port already exists
        FILE_FLAG_OVERLAPPED,           // Asynchronous I/O
        NULL                            // No template file for COM port
        );

    if ( _hSerialPort == INVALID_HANDLE_VALUE )
    {
        TRACE(_T("CSerialPort::Open : Failed to get the handle to the serial port.\r\n\tError: %d\r\n\tFile: %s\r\n\tLine: %d\r\n"), ::GetLastError(), __WFILE__, __LINE__);
        return ::GetLastError();
    }

    /* Initialize the DCB structure with COM port parameters with BuildCommDCB. */

    /* Set the serial port communications events mask with SetCommMask. */

    /* Set serial port parameters with SetCommState. */

    /* Set the serial port communications timeouts with SetCommTimeouts. */

    /* Create thread to handle received data with CreateThread. */

    free( pwcPortName );                 // <-- Exception thrown here.

    return dwRetVal;
}
Run Code Online (Sandbox Code Playgroud)

谁能告诉我我做错了什么?谢谢.

Ste*_*end 7

malloc分配字节,但您使用分配的内存来存储wchar_t.

您必须更改mallocsize参数以匹配现有memcpy用法:

pwcPortName = (wchar_t *)malloc( wcslen( port ) + 6 );
Run Code Online (Sandbox Code Playgroud)

应该

pwcPortName = (wchar_t *)malloc( (wcslen( port ) + 6) * sizeof(wchar_t));
Run Code Online (Sandbox Code Playgroud)