[問題] 關於free()不同型態的指標

看板C_and_CPP (C/C++)作者 (Archer55b6)時間7年前 (2018/12/22 11:32), 7年前編輯推噓0(006)
留言6則, 1人參與, 7年前最新討論串1/1
開發平台(Platform): Win10 編譯器:gcc in minGNU for windows + NotePad++ 額外使用到的函數庫(Library Used): 無 問題(Question): 在練習資料結構的graph時,用到一個destroy_graph的函數, 功能是將整個graph所占用到的空間都free掉 但由於引入的dataPtr 是用void*,想請問若不管使用者丟進來的 dataPtr是指向什麼變數型態,直接在graph的副程式中free(dataPtr), 如此會造成memory leakage嗎? 編譯器又是如何去判定free(ptr) 中的這個ptr是指向什麼資料型態、 該free多少單位的memory呢? 程式碼(Code):(請善用置底文網頁, 記得排版,禁止使用圖檔) http://codepad.org/FET3H7It 補充說明(Supplement): -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 36.227.0.168 ※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1545449563.A.8A3.html ※ 編輯: Archer55b6 (36.227.0.168), 12/22/2018 11:36:44 ※ 編輯: Archer55b6 (36.227.0.168), 12/22/2018 11:40:11 ※ 編輯: Archer55b6 (36.227.0.168), 12/22/2018 11:42:33 ※ 編輯: Archer55b6 (36.227.0.168), 12/22/2018 11:48:42

12/22 12:02, 7年前 , 1F
1.free本來就吃void*, 會leak豈不砂鍋大的bug
12/22 12:02, 1F

12/22 12:03, 7年前 , 2F
2.編譯器本身不管,memory allocator本身自已實作的問題
12/22 12:03, 2F

12/22 12:03, 7年前 , 3F
3.依實作,在C的malloc/free,其實只要能想辦法知道addr與
12/22 12:03, 3F

12/22 12:04, 7年前 , 4F
size的關係就好了. 最智障就查表, 通常是前面塞header
12/22 12:04, 4F

12/22 12:05, 7年前 , 5F
header通常是串回memory pool, 一些use/free list之類的
12/22 12:05, 5F

12/22 12:06, 7年前 , 6F
有興趣可以找 dlmalloc 的實作, 最單純
12/22 12:06, 6F
感謝cole大的解釋,之後再練習實作看看doug lee's acllocater! ※ 編輯: Archer55b6 (36.227.0.168), 12/22/2018 15:34:54
文章代碼(AID): #1S7R1RYZ (C_and_CPP)
文章代碼(AID): #1S7R1RYZ (C_and_CPP)