为结构内的结构分配内存

时间:2016-05-11 23:09:49

标签: c struct malloc

typedef struct{
    char id[15];
    int count;
}hashtag;

typedef struct node{
    hashtag *hashtag;
    struct node*next;
}*link;

我正在编写一个程序来读取句子中的主题标签,我想将它们存储在列表中。我已经定义了这两个结构,我可以读取并将标签传递给下面的函数但我需要帮助分配内存以便将字符串复制到列表中。

void check_insert(char newh[]){
    link x;
    //malloc to allocate memory for the string I want to copy

    strcpy(x->hashtag->id, newh);
    x->hashtag->count += 1;
    head = insert_end(head, x->hashtag); //head is a global variable that points to the 1st element of the list
}

1 个答案:

答案 0 :(得分:1)

您应该在x中分配和初始化指针check_insert,取消引用它并在没有首先分配的情况下访问其成员是未定义的行为:

void check_insert(char newh[]){
    link x = malloc(sizeof *x);
    x->hashtag = malloc(sizeof *x->hashtag);

    // strcpy(x->hashtag->id, newh); <-- UB if newh is larger than 14 in size
    x->hashtag->id[0] = '\0';
    strncat(x->hashtag->id, newh, sizeof(x->hashtag->id));
    x->hashtag->count = 1;
    head = insert_end(head, x->hashtag);
}