我试图使用 malloc 分配内存,我无法理解为什么这两个 malloc 调用会得到不同的结果。
The line below gives me wrong result even though with gdb I see the data is getting the correct value assigned.
nodeptr n = malloc(sizeof(nodeptr));
值头->数据:'!'
值 head->eq->data: ''
And when I do this get the correct result:
nodeptr n = malloc(sizeof(struct Node));
值头->数据:'w'
值 head->eq->data: 'X'
我关注了this帖子,我认为我做对了。
在这两种方式中,在分配时我获得了相同数量的内存,只是我最终看到了不同的结果。
typedef struct Node
{
struct Node *left, *right, *eq;
char data;
bool isEnd;
} *nodeptr;
nodeptr newNode(const char c) {
nodeptr n = malloc(sizeof(nodeptr));
// nodeptr n = malloc(sizeof(struct Node));
n->data = c;
n->left = NULL;
n->right = NULL;
n->left = NULL;
n->isEnd = false;
return n;
}
void insert(nodeptr *node, const char *str) {
if (*node == NULL) {
*node = newNode(*str);
}
nodeptr pCrawl = *node;
if(pCrawl->data < *str) {
insert(&pCrawl->right, str);
} else if (pCrawl->data > *str) {
insert(&pCrawl->left, str);
} else {
if(*(str+1)) {
insert(&pCrawl->eq, str + 1);
} else {
pCrawl->isEnd = true;
}
}
}
int main(int argc, char const *argv[])
{
const char* const strs[5]= {
"w.",
};
nodeptr head = NULL;
for(int i = 0; i<1; i++) {
insert(&head, strs[i]);
}
return 0;
printf("Value head->data: \'%c\'\n", head->data);
printf("Value head->eq->data: \'%c\'\n", head->eq->data);
}
最佳答案
sizeof(nodeptr)
== sizeof(结构节点*)
!= sizeof(struct Node)
== sizeof( *nodeptr)
sizeof(nodeptr)
将始终是指针的大小(如 64 位 CPU 上的 8 个字节)sizeof(struct Node)
引用结构体内容sizeof(*nodeptr)
等同于sizeof(struct Node)
,其中包含额外的取消引用运算符。
它可能看起来“有效”(不是段错误)的原因是 malloc
从更大的堆内存块中进行再分配。但是,代码正在写入所请求分配的越界,这最终可能会在某些时候导致堆损坏或段错误。
关于c - malloc(sizeof(struct Node)) 与 malloc(sizeof(nodeptr)) 的不同行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57032510/