[問題] malloc issue

看板C_and_CPP (C/C++)作者 (easyget)時間10年前 (2015/12/06 11:56), 編輯推噓1(105)
留言6則, 3人參與, 最新討論串1/1
開發平台(Platform): (Ex: VC++, GCC, Linux, ...) C ( code-block ) 問題(Question): 練習 tree traversal 時,有時候編譯 okay, 有時候又會掛掉 每次只要掛掉,都是在第 4 次 malloc 時死掉的 有大大知道是什麼原因嗎 ? 謝謝解答囉... ---- 下面是編譯在網頁的程式碼 http://codepad.org/cGbffeBr 程式碼(Code):(請善用置底文網頁, 記得排版) // Listing_05_01 // Tree Traversal #include <stdio.h> #include <stdlib.h> #define SIZE 9 typedef struct node * treePointer; typedef struct node { char data; treePointer leftChild, rightChild; }; treePointer init(void); void inorder(treePointer ptr); int main(void) { treePointer start; start = init(); inorder(start); return 0; } treePointer init(void) { treePointer tree[SIZE]; int i; for(i = 0; i < SIZE; i++){ printf("%d\n", i); tree[i] = malloc(sizeof(tree[i])); tree[i]->leftChild = NULL; tree[i]->rightChild = NULL; } // tree initial tree[0]->data = '+'; tree[0]->leftChild = tree[1]; tree[0]->rightChild = tree[2]; tree[1]->data = '*'; tree[1]->leftChild = tree[3]; tree[1]->rightChild = tree[4]; tree[2]->data = 'E'; tree[3]->data = '*'; tree[3]->leftChild = tree[5]; tree[3]->rightChild = tree[6]; tree[4]->data = 'D'; tree[5]->data = '/'; tree[5]->leftChild = tree[7]; tree[5]->rightChild = tree[8]; tree[6]->data = 'C'; tree[7]->data = 'A'; tree[8]->data = 'B'; return tree[0]; } void inorder(treePointer ptr) { // in-order traversal if(ptr){ inorder(ptr->leftChild); printf("%c", ptr->data); inorder(ptr->rightChild); } } -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 1.171.33.106 ※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1449374214.A.048.html

12/06 12:23, , 1F
tree[i] = malloc(sizeof(tree[i])); //這行錯了
12/06 12:23, 1F

12/06 12:24, , 2F
仔細回想送進 malloc 的是誰的 sizeof
12/06 12:24, 2F

12/06 13:29, , 3F
將 sizeof(treePointer) 改成 sizeof(struct node) 後
12/06 13:29, 3F

12/06 13:30, , 4F
一切就正常了, 謝謝大大的說明 (原來我之前很多錯誤>"<)
12/06 13:30, 4F

12/06 15:33, , 5F
sizeof(*tree[i])比較容易理解
12/06 15:33, 5F

12/06 16:00, , 6F
謝謝大大,這樣確實比較容易閱讀
12/06 16:00, 6F
文章代碼(AID): #1MOx8618 (C_and_CPP)
文章代碼(AID): #1MOx8618 (C_and_CPP)