c-写入组件时出现分段故障



我正在编写一个小程序来与USB到UART桥(CP210x(通信。

该程序相当简单,但当我将出站消息数组的大小减小到(wm_size<25(以下时,就会出现分段错误。产生分段故障的代码如下所示:

HANDLE prog_com_port;
prog_com_port = CreateFileA("\\.\COM4",
GENERIC_READ | GENERIC_WRITE,   //Request Read and Write Acess
0,                              //Block others from sharing Acess
NULL,                           //Disable Security features
OPEN_EXISTING,                  //Only open existing device
FILE_ATTRIBUTE_NORMAL,          //Used to set atributes and flags
NULL); 
//Handle to 
if(prog_com_port == INVALID_HANDLE_VALUE)
{
printf("Opening COM port failed - INVALID_HANDLE_VALUEn");
CloseHandle(prog_com_port);
return 1;
}
else
printf("COM port was opened successfully n");
SetupCommState(prog_com_port);
Sleep(2);
#define wm_size 25
int messageLength = 2;
char W_message[wm_size] = {0x01,0x01}; 
long unsigned int * bytes_sent;
BOOL Status;
Status = WriteFile(prog_com_port,                       // Handle to the Serial port
&W_message,                             // Pointer to message buffer
messageLength,                          // No of bytes to write
bytes_sent,                             // Pointer to number of bytes written
NULL);
if(!Status)
{
printf("Failed to write to COM port - 0x00 n");
CloseHandle(prog_com_port);
return 2;
}

CloseHandle(prog_com_port);

我的逻辑告诉我,设置wm_size=2就足够了,但显然这是错误的。有人能告诉我为什么吗?

我用wm_size大小玩了一下,根据经验,25解决了这个问题。

wm_size = 2就足够了,问题在其他地方:bytes_sent是一个指向任何地方的指针。

您的";"修复";没有解决任何问题。您正在经历未定义的行为(包括显然工作良好(。

你想要这个(所有评论都是我的(:

DWORD messageLength = 2;               // use DWORD
DWORD bytes_sent;                      // use DWORD
char W_message[] = {0x01,0x01};        // you don't need wm_size
Status = WriteFile(prog_com_port,
W_message,             // remove &, W_message decays into a pointer
messageLength,
&bytes_sent,           // put &, you need a pointer here
NULL);

甚至更好:您不需要messageLength:

Status = WriteFile(prog_com_port,
W_message,              // remove &
sizeof(W_message),      // assuming W_message contains chars
&bytes_sent,            // put &
NULL);
// now bytes_sent contains the number of bytes sent (hopefully 2),
// providing WriteFile succeeded (Status is TRUE)

强烈建议使用DWORD,因此传递给WriteFile的参数类型实际上与声明(和文档(匹配。还要注意,所有Microsoft文档和头文件中的LPDWORD是与CCD_ 7相同。

最新更新