【发布时间】:2018-12-28 10:16:52
【问题描述】:
我需要使用我自己的协议与服务器和一些发送数据的望远镜通信。通讯完成后,我拆分消息以了解它是什么情况。连接和断开连接都可以正常工作,但拆分数据会导致核心转储(realloc(): invalid next size)。
Connection 发送此消息:0x01[]10[Telescope1]
断开连接发送此消息:0x02[]10[Telescope1]
发送数据发送此消息:0x03[METADATA]22[.txt&15&someRandomDate]
我打算将这些消息拆分为 type (0x03)、header (METADATA)、lenght of data field (22) 和 数据 (.txt&15&someRandomDate)。
经过一些测试,我得出的结论是由于字符串的大小。为了调试,在发送数据时,我使用了连接消息,并且拆分可以正常工作(每个文件都正确返回)。
然后我会逐渐将它逐个字符地更改为应该拆分的内容,并将此消息拆分为 0x03[METADA]10[Telescope1](大小 26),但不是 0x03[METADAT]10[Telescope1](大小 27)。在第二种情况下,它将输出以下内容:
string to split: 0x03[METADAT]10[Telescope1]
copying type 0
realloc of size 1
copying type x
realloc of size 2
realloc(): invalid next size
Aborted (core dumped)
所以它会读取 0x 并且它们会转储核心。 如果我通过在消息中添加随机文本使连接或断开连接字符串大于 27 个字符,也会导致核心转储。
这是我拆分字符串的代码。这很糟糕,因为我总是与 malloc 和 reallocs 斗争,所以提前抱歉。
Data read_data (char* string){
printf("string to split: %s\n", string);
Data d;
int i = 0;
char *aux = (char *) malloc(1);
while (string[i] != '[' || string[i] == '\0'){
printf("copying type %c\n", string[i]);
printf("realloc of size %d\n", (i + 1));
aux = (char *) realloc(aux, (i + 1));
//here also tried aux = (char *) realloc(aux, (i + 1) * sizeof(char*)); didn't work
strcpy(&aux[i], &string[i]);
i++;
}
aux[i] = '\0';
d.type = aux[3];
i++;
int j = 0;
aux = (char *) malloc(1);
while (string[i] != ']' || string[i] == '\0'){
printf("copying header %c\n", string[i]);
aux = (char *) realloc(aux, j + 1);
strcpy(&aux[j], &string[i]);
i++;
j++;
}
aux[j] = '\0';
d.header = aux;
i++;
j = 0;
aux = (char *) malloc(1);
while (string[i] != '[' || string[i] == '\0'){
printf("copying size %c\n", string[i]);
aux = (char *) realloc(aux, j + 1);
strcpy(&aux[j], &string[i]);
i++;
j++;
}
aux[j] = '\0';
d.length = atoi(aux);
i++;
j = 0;
aux = (char *) malloc(1);
while (string[i] != ']' || string[i] == '\0'){
printf("copying data %c\n", string[i]);
aux = (char *) realloc(aux, j + 1);
strcpy(&aux[j], &string[i]);
i++;
j++;
}
aux[j] = '\0';
d.data = aux;
return d;
}
我该如何解决这个问题?为什么它是一个较短的字符串可以正常工作?
编辑:正如 Spikatrix 指出的,如果我使用 aux[i] = string[i]; 而不是 strcpy(&aux[i], &string[i]); 工作正常
【问题讨论】:
-
试试
aux[i] = string[i];而不是strcpy(&aux[i], &string[i]); -
@Spikatrix 兄弟,你是个天才。工作正常。非常感谢!
-
你学会
for()循环了吗?使用它们!
标签: c dynamic-memory-allocation realloc