malloc上释放对象的校验和不正确
我得到了
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
以下函数中的错误:
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; }
我怎样才能做到这一点? 当我重写函数以使用path[path_len + 1]
分配内存时,它工作得很好。
现在,我不明白的部分是,我甚至从未在我的应用程序的任何一点上调用free
,因为程序需要每个分配的内存,直到它存在(其中,AFAIK无论如何都会使每个分配的内存无效?!)
那么,如果我从来没有释放一个被释放的对象怎么会被腐败呢?
该函数在此调用:
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 ", " "));
有realloc
,我使用那个错误吗? 我想阅读完整的服务器响应,所以我必须在每次迭代后重新分配,不是吗?
在read_response
,您可能会覆盖buf
的缓冲区的末尾。
问题是buf是一个指针,因此sizeof(buf)
将返回一个指针的大小(可能是4或8,具体取决于你的CPU)。 你正在使用sizeof
,好像buf
是一个数组,这与C中的指针实际上并不相同,尽管它们在某些情况下似乎是可互换的。
您需要跟踪为buf
分配的最后一个大小,而不是使用sizeof
,并在每次放大缓冲区时添加BUF_SIZE
。
您还应该考虑每次调用时read
操作可能返回的字符数比BUF_SIZE
少得多,因此在每次迭代中对buf
进行重新分配可能会过度。 但是,就正确性而言,这可能不会对您造成任何问题; 它只会使用比它需要更多的内存。
我会做更像下面的代码。
#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; } }
这个版本的优点是,如果read
调用只返回几个字节的数据,则不会尝试分配更多空间。
这条线
buf = realloc(buf, sizeof(buf) + BUF_SIZE);
是错的。 所有重新分配都具有相同的大小, BUF_SIZE + sizeof(char*)
。 然后在从套接字读取时写入未分配的内存,通过realloc
覆盖以前free
内存。
你必须跟踪分配的大小,
size_t current_buf_size = BUF_SIZE; /* ... */ char *temp = realloc(buf, current_buf_size + BUF_SIZE); if (temp == NULL) { /* die or repair */ } buf = temp;