【发布时间】:2018-05-18 08:34:49
【问题描述】:
下面的代码尝试初始化一个节点,并在这样做时动态初始化一个指向子节点的指针数组。但是,当我尝试访问孩子时,我得到了Segmentation fault: 11。我意识到我不应该得到任何有意义的值(即它只会在内存中成为垃圾),但我不知道为什么会出现分段错误。
#include <stdlib.h>
#include <assert.h>
#include <stdio.h>
#include <string.h>
#define INIT_SIZE 10
typedef struct node_t node_t;
struct node_t {
char *word;
node_t **children;
int arr_len;
};
void set_array_vals(node_t *root);
int main(int argc, char const *argv[]) {
char *word = "hello";
node_t *root = malloc(sizeof(node_t));
assert(root);
root->children = malloc(sizeof(node_t *) * INIT_SIZE);
assert(root->children);
root->arr_len = INIT_SIZE;
root->word = malloc((sizeof(char)) * (strlen(word) + 1));
assert(root->word);
strcpy(root->word, word);
set_array_vals(root);
printf("Arr len: %d\n", root->arr_len);
return 0;
}
void set_array_vals(node_t *root) {
int i;
for (i=1; i<root->arr_len; i++) {
node_t *this_node = root->children[i];
printf("%d: %d\n", i, this_node->arr_len);
}
}
【问题讨论】:
-
您已经为包含指向子节点的指针的数组分配了内存,但实际上并没有为子节点分配内存。
-
计算你拥有的
malloc(sizeof(node_t))的数量和你期望的节点数量。 -
啊,你是对的。所以从这里开始,我应该为每个数组位置(指向节点的指针)分配一个节点来为孩子分配内存?
-
没错,你可以在
set_array_vals本身的循环中做。 -
请不要更改关于答案的问题。这使答案看起来错误。能否请您回滚到修订版 1?
标签: c memory-management tree