- 論壇徽章:
- 14
|
本帖最后由 lxyscls 于 2015-10-08 12:29 編輯
回復(fù) 3# 何必抱怨 - void
- public_fREe(void* mem)
- {
- mstate ar_ptr;
- mchunkptr p; /* chunk corresponding to mem */
- void (*hook) (__malloc_ptr_t, __const __malloc_ptr_t)
- = force_reg (__free_hook);
- if (__builtin_expect (hook != NULL, 0)) {
- (*hook)(mem, RETURN_ADDRESS (0));
- return;
- }
- if (mem == 0) /* free(0) has no effect */
- return;
- p = mem2chunk(mem);
- ... ...
- ar_ptr = arena_for_chunk(p);
- _int_free(ar_ptr, p, 0);
- }
復(fù)制代碼 對(duì)于較小的內(nèi)存分配,都在chunk里面分配,使用_init_free()。- static void
- _int_free(mstate av, mchunkptr p, int have_lock)
- {
- INTERNAL_SIZE_T size; /* its size */
- mfastbinptr* fb; /* associated fastbin */
- mchunkptr nextchunk; /* next contiguous chunk */
- INTERNAL_SIZE_T nextsize; /* its size */
- int nextinuse; /* true if nextchunk is used */
- INTERNAL_SIZE_T prevsize; /* size of previous contiguous chunk */
- mchunkptr bck; /* misc temp for linking */
- mchunkptr fwd; /* misc temp for linking */
- const char *errstr = NULL;
- int locked = 0;
- size = chunksize(p);
- ... ...
- /*
- If eligible, place chunk on a fastbin so it can be found
- and used quickly in malloc.
- */
- if ((unsigned long)(size) <= (unsigned long)(get_max_fast ())
- ... ...
- set_fastchunks(av);
- unsigned int idx = fastbin_index(size);
- fb = &fastbin (av, idx);
- mchunkptr fd;
- mchunkptr old = *fb;
- unsigned int old_idx = ~0u;
- do
- {
- /* Another simple check: make sure the top of the bin is not the
- record we are going to add (i.e., double free). */
- if (__builtin_expect (old == p, 0))
- {
- errstr = "double free or corruption (fasttop)";
- goto errout;
- }
復(fù)制代碼 為什么free(p1);free(p1);會(huì)"double free",沒有細(xì)看代碼,我個(gè)人的理解是:兩次取得的chunk_size一樣,所以它認(rèn)為是"double free"。
為什么中間加了一個(gè)free(p2),就不會(huì)"double free"了,是因?yàn)樵賔ree(p1)的時(shí)候,chunk_size變了
因?yàn)閜1,p2的大小都是10,所以它們都在fastbin里面分配;如果把p2設(shè)置成一個(gè)比較大的值,比如13B,free(p1);free(p2);free(p1);一樣會(huì)"double free",因?yàn)閜2分配的chunk和p1不一樣,不影響第二次free(p1)時(shí)候的判斷
|
|