我的应用程序中有一个函数,其中分配内存以格式化端口名称。调用CreateFile
来打开端口。调用free
函数结束时会尝试释放分配的内存。免费分配内存产生异常 - C++
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;
}
有谁能告诉我我做错了什么吗?谢谢。
您对大小许多假设。通过适当地使用sizeof(wchar_t)来明确这些。也动态分配内存不是异常安全的查找RAII(在这种情况下也称为std :: vector/std :: wstring)。 – 2010-12-01 19:20:22