简体   繁体   中英

Malloc with struct

This is the code in C, compiled on Ubuntu 15.10:

----- 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);
    }

This is the console output, I can't understand why the string '8446000' appears. I tried the same code on Mac OS X and it works fine.

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));

This allocates size for the pointer, not the structure. Try this:

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

Similarly for other variables.

node is a pointer type and its size will be less than size of the struct, so there are insufficient space allocated and you are accessing out-of-range.

Try using sizeof(struct node_tree) instead of sizeof(node) .

I suggest you should stop using typedef to the pointer to avoid confusion.

This is one of the reasons you should not hide pointers behind typedef.

sizeof(node) returns sizeof(struct node_tree*) , not sizeof(struct node_tree) as you expect.

Change the typedef to not hide the pointer:

typedef struct node_tree node;

And to be safe, allocate using variable rather than type:

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

You need to allocate the right size:

node N = malloc(sizeof *N);

Try to print their size to see it:

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

EDIT: replaced type with variable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM