浏览代码

simplify and improve double-free check

a valid mmapped block will have an even (actually aligned) "extra"
field, whereas a freed chunk on the heap will always have an in-use
neighbor.

this fixes a potential bug if mmap ever allocated memory below the
main program/brk (in which case it would be wrongly-detected as a
double-free by the old code) and allows the double-free check to work
for donated memory outside of the brk area (or, in the future,
secondary heap zones if support for their creation is added).
Rich Felker 13 年之前
父节点
当前提交
ce7c6341d3
共有 1 个文件被更改,包括 2 次插入2 次删除
  1. 2 2
      src/malloc/malloc.c

+ 2 - 2
src/malloc/malloc.c

@@ -394,7 +394,7 @@ void *realloc(void *p, size_t n)
 		size_t oldlen = n0 + extra;
 		size_t oldlen = n0 + extra;
 		size_t newlen = n + extra;
 		size_t newlen = n + extra;
 		/* Crash on realloc of freed chunk */
 		/* Crash on realloc of freed chunk */
-		if ((uintptr_t)base < mal.brk) *(volatile char *)0=0;
+		if (extra & 1) *(volatile char *)0=0;
 		if (newlen < PAGE_SIZE && (new = malloc(n))) {
 		if (newlen < PAGE_SIZE && (new = malloc(n))) {
 			memcpy(new, p, n-OVERHEAD);
 			memcpy(new, p, n-OVERHEAD);
 			free(p);
 			free(p);
@@ -457,7 +457,7 @@ void free(void *p)
 		char *base = (char *)self - extra;
 		char *base = (char *)self - extra;
 		size_t len = CHUNK_SIZE(self) + extra;
 		size_t len = CHUNK_SIZE(self) + extra;
 		/* Crash on double free */
 		/* Crash on double free */
-		if ((uintptr_t)base < mal.brk) *(volatile char *)0=0;
+		if (extra & 1) *(volatile char *)0=0;
 		__munmap(base, len);
 		__munmap(base, len);
 		return;
 		return;
 	}
 	}