F.P*_*F.P 5 c malloc memory-leaks
我得到了
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
Run Code Online (Sandbox Code Playgroud)
以下函数中的错误:
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;
}
Run Code Online (Sandbox Code Playgroud)
我怎样才能做到这一点?当我重写函数以使用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 ", " "));
Run Code Online (Sandbox Code Playgroud)
有realloc,我使用那个错误?我想阅读完整的服务器响应,所以我必须在每次迭代后重新分配,不是吗?
在read_response,您可能会覆盖指向的缓冲区的末尾buf.
问题是buf是一个指针,因此sizeof(buf)将返回一个指针的大小(可能是4或8,具体取决于你的CPU).您正在使用sizeof,就好像buf是一个数组,这与C中的指针实际上并不相同,尽管它们在某些情况下似乎可以互换.
sizeof您需要跟踪分配的最后一个大小,而不是使用,buf并在BUF_SIZE每次放大缓冲区时添加.
您还应该考虑read操作可能返回比BUF_SIZE每次调用少得多的字符,因此在每次迭代中执行reallocon 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;
}
}
Run Code Online (Sandbox Code Playgroud)
此版本的优点是,如果read调用只返回几个字节的数据,则不会尝试分配更多空间.
这条线
buf = realloc(buf, sizeof(buf) + BUF_SIZE);
Run Code Online (Sandbox Code Playgroud)
是错的.所有重新分配都具有相同的大小BUF_SIZE + sizeof(char*).那么你是从套接字读取数据时,覆盖先前存储器写入未分配的内存free由D realloc.
你必须跟踪分配的大小,
size_t current_buf_size = BUF_SIZE;
/* ... */
char *temp = realloc(buf, current_buf_size + BUF_SIZE);
if (temp == NULL) {
/* die or repair */
}
buf = temp;
Run Code Online (Sandbox Code Playgroud)