Question

this is a part of my socket client , receive buffer is small than server's send buffer, so I need to realloc buffer, but it throw error like this:

malloc: *** error for object 0x7fd44ad00018: incorrect checksum for freed object - object was probably modified after being freed.

my code :

char recv_buf[MAX_RECV_LINE] = "";
while (fgets(buf, MAX_SEND_LINE, stdin) != NULL) {  
    write(servfd, buf, strlen(buf));
    char *recv_data = malloc(MAX_RECV_LINE);
    bzero(recv_data, MAX_SEND_LINE);
    int recv_size = 0;
    while (1) {
        FD_ZERO(&readfds);
        FD_SET(servfd, &readfds);
        select(servfd + 1, &readfds, NULL, NULL, &timeout);
        if (FD_ISSET(servfd, &readfds)) {
            bzero(recv_buf, MAX_RECV_LINE);
            size_t recv_buf_len = recv(servfd, recv_buf, MAX_RECV_LINE, 0);
            if (recv_buf_len == 0) {
                printf("Server is closed.\n");
                close(servfd);
                exit(0);
            }

            recv_data = realloc(recv_data, recv_size + recv_buf_len);
            if (recv_data == NULL) {
                exit(0);
            }
            printf("realloc: %lu\n", recv_size + recv_buf_len);
            memcpy(recv_data + recv_size, recv_buf, recv_buf_len);

            recv_size += recv_buf_len;
        } else {
            break;
        }
    }
    printf("total count: %d\n", recv_size);
    printf("Message: %s", recv_data);
    free(recv_data);
}

and recv_data can't get the completely message

Était-ce utile?

La solution

char *recv_data = malloc(MAX_RECV_LINE);
bzero(recv_data, MAX_SEND_LINE);

The problem is here. You're allocating a buffer of size MAX_RECV_LINE but zeroing it for a length of MAX_SEND_LINE, which you said is greater. You don't need to zero it at all actually: your code appears to deal with the received data correctly. Just remove the bzero() call completely.

But it would be a lot simpler to use the same buffer size at both ends. I always use 8192.

Autres conseils

Two suggestions:

  • You don't check if recv_buf_len is negative (e.g. from a signal). And its type should be ssize_t, not size_t.

  • IIRC, you need to redo timeout each time you call select (but this wouldn't be the cause of the problem).

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top