這是在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
而這,先生,這就是爲什麼我通常避免那種'typedef'。你必須*鍵入*少,但往往忘記什麼*實際*類型的東西。 – DevSolar
爲了澄清該評論,請注意是否將'typedef'和'struct'一起使用完全是一種風格問題。大多數C程序員使用'typedef struct',但不喜歡的Linux程序員除外。兩種風格都不是錯的。然而,在typedef_後面隱藏一個指針並不是一種風格問題,而只是糟糕而危險的編程實踐。 – Lundin