[問題] 為甚麼會segmentation fault?

看板C_and_CPP (C/C++)作者 (DOGE)時間6年前 (2019/10/16 19:25), 編輯推噓4(408)
留言12則, 7人參與, 6年前最新討論串1/1
int makeList(List_t* list) { list = malloc(sizeof(List_t)); if(!list){ return list_makeFail; }else{ return list_success; } } bool isEmpty(List* list) { return (list->head == NULL); } int main() { int ret; List_t* testList; ret = makeList(testList); printf("make list is %d\n", ret); ret = isEmpty(testList); printf("list is empty : %s\n", ret ? "true":"false"); return 0; } 測了一下是死在isEmpty() 另外試了一下: List_t testList = malloc(sizeof(List_t)); isEmpty(testList); 這樣是沒問題的,我是哪邊的觀念有錯誤嗎? 平台是centos7,用的是C -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 175.98.120.34 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1571225142.A.670.html

10/16 19:47, 6年前 , 1F
makeList裡面malloc的pointer沒傳出來
10/16 19:47, 1F

10/16 19:47, 6年前 , 2F
所以isEmpty一用就爆
10/16 19:47, 2F

10/16 20:56, 6年前 , 3F
沒看到 List_t 的宣告,但我猜你需要的是
10/16 20:56, 3F

10/16 20:56, 6年前 , 4F
a pointer to a pointer
10/16 20:56, 4F

10/17 00:57, 6年前 , 5F
因為愛
10/17 00:57, 5F

10/17 14:19, 6年前 , 6F
推三樓,另外可能也要複習一下 call by value 跟 pointer
10/17 14:19, 6F

10/17 20:58, 6年前 , 7F
兩種做法,不是用 ptr to ptr 就是回傳 malloc 拿到的
10/17 20:58, 7F

10/17 20:58, 6年前 , 8F
記憶體位置給 testList,你這實作比較適合用前者
10/17 20:58, 8F

10/18 16:50, 5年前 , 9F
pass pointer 變數到fun中會是一個副本(I.e copy)你的 mak
10/18 16:50, 9F

10/18 16:50, 5年前 , 10F
eList(List_t* list)中的list 不是你原本預期main裡面的test
10/18 16:50, 10F

10/18 16:50, 5年前 , 11F
list變數
10/18 16:50, 11F

02/28 15:31, 6年前 , 12F
在malloc後/ main內打印一下address就知道問題在哪了
02/28 15:31, 12F
文章代碼(AID): #1TflusPm (C_and_CPP)
文章代碼(AID): #1TflusPm (C_and_CPP)