Incorrect checksum for freed object on malloc

Viewed 46140

I get an

malloc: *** error for object 0x1001012f8: incorrect checksum for freed object
        - object was probably modified after being freed.
        *** set a breakpoint in malloc_error_break to debug

error in the following function:

char* substr(const char* source, const char* start, const char* end) {
    char *path_start, *path_end, *path;

    int path_len, needle_len = strlen(start);

    path_start = strcasestr(source, start);
    if (path_start != NULL) {
        path_start += needle_len;
        path_end = strcasestr(path_start, end);
        path_len = path_end - path_start;
        path = malloc(path_len + 1);
        strncpy(path, path_start, path_len);
        path[path_len] = '\0';
    } else {
        path = NULL;
    }

    return path;
}

How can I make this work? When I rewrite the function to allocate the memory using path[path_len + 1] it works just fine.

Now, the part I don't understand is, that I never even call free in any point of my application, as every allocated memory is needed for the program until it exists (which, AFAIK will invalidate every allocated memory anyway?!)

So, how can a freed object be corrupt if I never free one?

The function is called in this one:

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

    while ((bytes_read = read(sock, cur_position, BUF_SIZE)) > 0) {
        cur_position += bytes_read;
        buf = realloc(buf, sizeof(buf) + BUF_SIZE);
    }

    int status = atoi(substr(buf, "HTTP/1.0 ", " "));

There is the realloc, am I using that wrong? I want to read the complete server response, so I have to reallocate after every iteration, don't I?

2 Answers
Related