[問題] 為甚麼會segmentation fault?

作者: d630200x (DOGE)   2019-10-16 19:25:38
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
作者: ab4daa (nooooooooooooooooooo)   2019-10-16 19:47:00
makeList裡面malloc的pointer沒傳出來所以isEmpty一用就爆
作者: withoutshine (何必幫別人想那麼多)   2019-10-16 20:56:00
沒看到 List_t 的宣告,但我猜你需要的是a pointer to a pointer
作者: loveme00835 (髮箍)   2019-10-17 00:57:00
因為愛
作者: Ryspon (Ry)   2019-10-17 14:19:00
推三樓,另外可能也要複習一下 call by value 跟 pointer
作者: dces4212 (flawless)   2019-10-17 20:58:00
兩種做法,不是用 ptr to ptr 就是回傳 malloc 拿到的記憶體位置給 testList,你這實作比較適合用前者
作者: Gway (我愛的你 也愛我 好嗎?)   2019-10-18 16:50:00
pass pointer 變數到fun中會是一個副本(I.e copy)你的 makeList(List_t* list)中的list 不是你原本預期main裡面的testlist變數

Links booklink

Contact Us: admin [ a t ] ucptt.com