[英]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.