gpt4 book ai didi

c++ - 空闲分配的内存生成异常 - C++

转载 作者:塔克拉玛干 更新时间:2023-11-03 08:10:15 24 4
gpt4 key购买 nike

我的应用程序中有一个函数,其中分配内存用于格式化端口名称。 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;
}

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

最佳答案

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

您必须更改 malloc 大小参数以匹配您现有的 memcpy 用法:

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

应该是

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

关于c++ - 空闲分配的内存生成异常 - C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4325947/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com