簡體   English   中英

帶結構的Malloc

[英]Malloc with struct

這是在Ubuntu 15.10上編譯的C語言代碼:

----- 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
    node root = malloc(sizeof(node));

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

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

其他變量也是如此。

node是指針類型,其大小將小於結構的大小,因此分配的空間不足,您正在訪問范圍外。

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

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

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

sizeof(node)返回sizeof(struct node_tree*) ,而不是您期望的sizeof(struct node_tree)

將typedef更改為隱藏指針:

typedef struct node_tree node;

為了安全起見,請使用變量而不是類型進行分配:

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

您需要分配正確的大小:

node N = malloc(sizeof *N);

嘗試打印其大小以查看它:

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

編輯:用變量替換類型。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM