2016-04-14 65 views
1

這是在C中的代碼,在Ubuntu 15.10編譯:malloc的與結構

----- ----- node_tree.h

struct node_tree{ 
     int key; 
     char value[20]; 
     struct node_tree* right_child; 
     struct node_tree* left_child; 
    }; 
    typedef struct node_tree* node; 

----- tree_test_main.c -----

#include "node_tree.h" 
    #include <stdio.h> 
    #include <stdlib.h> 
    #include <assert.h> 
    #include <string.h> 
    #include <time.h> 

    int main(){ 
     //root 
     node root = malloc(sizeof(node)); 
     root->key = 1; 
     strcpy(root->value, "Ciao"); 

     //left child 
     node left = malloc(sizeof(node)); 
     left->key = 2; 
     strcpy(left->value, "Maremma"); 

     //right child 
     node right = malloc(sizeof(node)); 
     right->key = 3; 
     strcpy(right->value, "Maiala"); 

     root->left_child = left; 
     root->right_child = right; 

     printf("%d, %s\n", root->key, root->value); 
     printf("%d, %s\n", root->left_child->key, root->left_child->value); 
     printf("%d, %s\n", root->right_child->key, root->right_child->value); 

     free(root); 
     free(right); 
     free(left); 
    } 

這是控制檯輸出,我不明白爲什麼字符串'8446000'出現。 我在Mac OS X上嘗試了相同的代碼,它工作正常。

1, Ciao 
8446000, 
3, Maiala 
*** Error in `./a.out': free(): invalid next size (fast): 0x000000000080e010 *** 
[1] 3926 abort (core dumped) ./a.out 
+4

而這,先生,這就是爲什麼我通常避免那種'typedef'。你必須*鍵入*少,但往往忘記什麼*實際*類型的東西。 – DevSolar

+1

爲了澄清該評論,請注意是否將'typedef'和'struct'一起使用完全是一種風格問題。大多數C程序員使用'typedef struct',但不喜歡的Linux程序員除外。兩種風格都不是錯的。然而,在typedef_後面隱藏一個指針並不是一種風格問題,而只是糟糕而危險的編程實踐。 – Lundin

回答

3
node root = malloc(sizeof(node)); 

這爲指針,而不是結構分配大小。試試這個:

node root = malloc(sizeof(*root)); 

類似的其他變量。

+0

'node'是一個類型名稱,'* node'會發出編譯錯誤。 – MikeCAT

+0

@MikeCAT我的意思是'root' –

1

您需要分配適當的大小:

node N = malloc(sizeof *N); 

嘗試打印它們的大小,看它:

printf("sizeof N = %zu", sizeof N); 
printf("sizeof *N = %zu", sizeof *N); 

編輯:更換同類型變量。

+0

'node'是一個類型名稱,'* node'會發出編譯錯誤。 – MikeCAT

2

node是一個指針類型,其大小將小於該結構的大小,因此沒有足夠的空間分配並且您正在訪問超出範圍。

嘗試使用sizeof(struct node_tree)而不是sizeof(node)

我建議你應該停止使用typedef指針以避免混淆。

2

這是您不應該在typedef後面隱藏指針的原因之一。

sizeof(node)返回sizeof(struct node_tree*),而不是sizeof(struct node_tree)如您所料。

更改的typedef 隱藏指針:

typedef struct node_tree node; 

,注意安全,分配使用變量,而不是類型:

node * root = malloc(sizeof(*root)); 
+0

謝謝你,現在它工作 – Davix33