Incorrect checksum for freed object on malloc

In read_response, you are probably overwriting the end of the buffer pointed to by buf.

The problem is that buf is a pointer, so sizeof(buf) will return the size of a pointer (probably 4 or 8 depending on your CPU). You are using sizeof as if buf were an array, which is not really the same thing as a pointer in C although they seem interchangeable in some contexts.

Instead of using sizeof, you need to be keeping track of the last size that you allocated for buf, and add BUF_SIZE to that each time you enlarge the buffer.

You should also consider that the read operation may be returning considerably fewer characters than BUF_SIZE on each call, so doing a realloc on buf in each iteration may be overkill. That probably won’t cause any problems for you in terms of correctness, though; it will just use more memory than it needs to.

I would do something more like the code below.

#define MIN_BUF_SPACE_THRESHOLD (BUF_SIZE / 2)

char *read_response(int sock) {
    int bytes_read;
    char *buf = (char*)malloc(BUF_SIZE);
    int cur_position = 0;
    int space_left = BUF_SIZE;

    if (buf == NULL) {
        exit(1); /* or try to cope with out-of-memory situation */
    }

    while ((bytes_read = read(sock, buf + cur_position, space_left)) > 0) {
        cur_position += bytes_read;
        space_left -= bytes_read;
        if (space_left < MIN_BUF_SPACE_THRESHOLD) {
            buf = realloc(buf, cur_position + space_left + BUF_SIZE);
            if (buf == NULL) {
                exit(1); /* or try to cope with out-of-memory situation */
            }
            space_left += BUF_SIZE;
        }
    }

This version has the advantage of not trying to allocate more space if the read call comes back with only a few bytes of data.

Leave a Comment