gpt4 book ai didi

c - 在循环中发送数据会导致 malloc 内存损坏

转载 作者:太空宇宙 更新时间:2023-11-04 08:00:09 28 4
gpt4 key购买 nike

我正在处理有关套接字网络的作业,并且有一个客户端和一个服务器可以很好地连接和通信,只要我当时只发送对一条数据的请求。例如,一旦我发送了 5 条数据的请求,服务器就会因 malloc 内存损坏而崩溃。

我有:

int number_of_jobs;
msg[0] = '0';

read(sd, &number_of_jobs, 4);

for(int i = 0; i < number_of_jobs; i++){
printf("Total bytes read: %lu\n", total_bytes_read);
printf("Size: %lu\n", size);
printf("i: %d\n", i);
char jobtype;
unsigned int len;
fread(&jobtype, sizeof(jobtype), 1, fp);
DEBUG_PRINT(("\n>>%d<< Jobtype: %c\n", getpid(), jobtype));

fread(&len, 4, 1, fp);
DEBUG_PRINT((">>%d<< Len: %d\n", getpid(), len));

header = make_header(jobtype, len, size);

read_line = malloc(sizeof(char)*len + 1);
int n = fread(read_line, sizeof(char), len, fp);
if(n <= 0){
printf(">>%d<< ", getpid());
perror("Fread error");
}
*(read_line + strlen(read_line)-1) = '\0';
total_bytes_read += strlen(read_line);

package = malloc(sizeof(char)*40 + sizeof(char)* strlen(read_line+1));

strncpy(package, header, 41);
strcat(package, read_line);

printf("%s\n", package);

if(write(sd, package, strlen(package)) < 0){
printf(">>%d<< ", getpid());
perror("Write error");
}
printf("Writing %zu bytes\n", strlen(read_line));

free(package);
free(header);
free(read_line);
}

我知道这与覆盖内存有关(至少我这么认为?),但我不知道在哪里或为什么。

有效的部分基本上是 for i < number_of_jobs 部分中的所有内容,我可以根据需要多次调用它。

最佳答案

是什么让您认为 read_line 以 null 结尾来调用 *(read_line + strlen(read_line)-1) = '\0';?如果您需要使其以 null 结尾,您最好编写 read_line[n] = '\0'。之后也不需要调用 strlen,因为您已经知道您已经读取了 n 个字节。

关于c - 在循环中发送数据会导致 malloc 内存损坏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47290623/

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