简体   繁体   English

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

[英]Sending data in a loop causes malloc memory corruption

I'm working on an assignment on socket networking, and have a client and a server that connect and communicate fine, as long as I only send requests for one piece of data at the time. 我正在做套接字网络上的任务,并且有一个客户端和一个服务器可以很好地连接和通信,只要我当时只发送对一个数据的请求即可。 Once I send a request for for example 5 pieces of data, the server crashes due to malloc memory corruption. 一旦我发送了例如5条数据的请求,服务器就会由于malloc内存损坏而崩溃。

I have: 我有:

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);
}

I know it's something to do with overwriting memory (at least I think so?), but I don't know where or why. 我知道这与覆盖内存有关(至少我是这样认为的),但是我不知道在哪里或为什么。

The part that works, is essentially everything inside the for i < number_of_jobs part, which I can call as many times as I want. 有效的部分实质上是i <number_of_jobs部分中的所有内容,我可以调用任意多次。

What makes you think that read_line is null-terminated to call *(read_line + strlen(read_line)-1) = '\\0'; 是什么让您认为read_line是终止于null的值,以调用*(read_line + strlen(read_line)-1) = '\\0'; ? If you need to make it null-terminated you better write read_line[n] = '\\0' . 如果需要使它以null终止,则最好编写read_line[n] = '\\0' Also there is no need to call strlen afterwards since you already know that that you've read n bytes. 同样,您也无需事后调用strlen ,因为您已经知道已经读取了n个字节。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM