这是我在 Visual Studio 2008 中编写的代码。我在接收数组中获取数据并使用该数据,我正在准备对其进行响应。但我收到错误“server.exe 中 0x0f6cf9c4 处未处理的异常:0xC0000005:访问冲突读取位置 0x00000001”。每次在代码运行时的“strcat”函数处。
byte Receive[50];
unsigned char result[50];
int index = 0;
char *type;
char *s = "ff ff ff 1d 00 01 01 0b 00 01";
char *s1 = "03 00 98 ac 06 36 6f 92";
int i;
if (Receive[i] == 0x18)
{
if ((Receive[i+1] == 0x20) || (Receive[i+1] == 0x21) || (Receive[i+1] == 0x22) || (Receive[i+1] == 0x23) || (Receive[i+1] == 0x24) || (Receive[i+1] == 0x25))
{
if (Receive[i+2] == 0x00)
{
result[index] = Receive[i-4];`enter code here`
result[index+1] = Receive[i-3];
index = index+2;
type = "report";
}
}
}
}
index = 0;
if (type == "report")
{
strcat(s, result[index]);
strcat(s, result[index+1]);
strcat(s, s1);
strcat(s, array1[j]);
strcat(s, array1[j+1]);
strcat(s, array1[j+2]);
strcat(s, array1[j+3]);
strcat(s, array1[j+4]);
最佳答案
导致崩溃的一个可能原因是您尝试修改字符串文字。
当您执行 strcat(s, ...)
时,您会修改 s
指向的字符串文字。字符串文字是一个只读的固定大小的字符数组,以特殊字符 '\0'
结尾。当您在 strcat
调用中使用此类字符串文字作为目标时,您将首先修改只读数组,然后写入超出数组范围的内容。这两件事都会导致未定义的行为。
您需要创建自己的数组,该数组足够大以容纳您要写入的所有数据。并且不要忘记字符串终止符的空格。
此外您使用例如结果[索引]
作为字符串。 result
中的元素是单个字符,而不是指向字符串的指针。为此,您需要使用 strncat
仅连接单个字符。 并且您需要将指针传递给角色。根据 array1
的不同,可能会出现类似的问题。
作为另一种可能的解决方案,您可能希望使用 sprintf
而不是一系列无效的 strcat
调用:
sprintf(dest, "%s%c%c%s%c%c%c%c%c",
s,
result[index],
result[index+1],
s1,
array1[j],
array1[j+1],
array1[j+2],
array1[j+3],
array1[j+4]);
关于c - server.exe : 0xC0000005: Access violation reading location 0x00000001 中 0x0f6cf9c4 处出现未处理的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40482239/