0
我有以下結構:爲什麼下面的C代碼被髮送SIGSEGV信號?
typedef struct binTree_t {
int key;
enum {lMore, rMore, equal} ratio;
struct binTree_t* parent;
struct binTree_t* left;
struct binTree_t* right;
struct binTree_t** root;
} binTree_t;
表示AVL樹。這個問題似乎是根雙指針。這個想法是,這種方式更改爲*(node->root)
將傳播到指向相同的node->root
的所有節點。這種雙重抽象應確保**(node->root)
始終指向正確的根節點。然而,似乎是我分配的內存的方式有問題:
binTree_t* createNode(int key, binTree_t* root) {
binTree_t* node = malloc(sizeof(binTree_t));
node->key = key;
node->ratio = equal;
node->parent =
node->left =
node->right = NULL;
node->root = root?&root:&node;
return node;
}
下面的代碼都正確返回12
:
int main(void) {
binTree_t* root = createNode(12, NULL);
printf("%d", root->key); free(root);
return EXIT_SUCCESS;
}
int main(void) {
binTree_t* root = createNode(12, NULL);
printf("%d", (*(root->root))->key); free(root);
return EXIT_SUCCESS;
}
下面的代碼,但是,返回12
和0
:
int main(void) {
binTree_t* root = createNode(12, NULL);
printf("Text");
printf("%d", root->key); free(root);
return EXIT_SUCCESS;
}
int main(void) {
binTree_t* root = createNode(12, NULL);
printf("Text");
printf("%d", (*(root->root))->key); free(root);
return EXIT_SUCCESS;
}
看起來好像root->root
指針被分配在的堆棧上功能?如果是這樣,你如何建議我修復它,以便它使用mallocated內存?
哦,我還需要malloc指針,不是嗎?謝謝。 – Witiko