转移结构时使用不正确的memcopy()

时间:2018-02-11 13:26:50

标签: c

我有两个结构

struct word_count_struct 
{
    char *word;
    int count;
};

struct bag_struct 
{
    struct word_count_struct *bag;
    int bag_size;
    int total_words;
};

我试图通过使用memcopy将word_count_struct的副本放入* bag。我不太清楚为什么,但是每当我的程序试图将word_count_struct存储到* bag时,我就会出现分段错误。我认为这可能与我正在使用的memcopy的争论有关:

struct bag_struct *bow;
struct word_count_struct *WCS;
    bow = realloc(bow,sizeof(struct word_count_struct) * (bow->bag_size + 1));
    memcpy(&(bow->bag) + bow->bag_size ,WCS, sizeof(struct word_count_struct));

我没有在这里显示它,但是bow和WCS都被正确的值初始化(除了bow.bag)。

2 个答案:

答案 0 :(得分:0)

此表达式很可能不正确:&(bow->bag) + bow->bag_size

bow->bag的地址位于bag_struct结构内。向它添加bow->bag_size会为您提供一个超过bag_struct末尾的指针,从而导致未定义的行为。您想要的是&(bow->bag[bow->bag_size])或此bow->bag+bow->bag_size

memcpy(bow->bag+bow->bag_size, WCS, sizeof(*bag));

答案 1 :(得分:0)

这完全是完全混淆了。

您只需一个 bag_struct。 bag_struct可以包含任意数量的word_count_struct。 bow应该只是一个struct bag_struct,正确初始化为bag_size = 0,total_words = 0,bag = NULL。

重新分配的东西是bow.bag,大小为(bag_size + 1)* sizeof(word_count_struct)。并通过指定bow.bag [bow.bag_size] = * WCS并增加bow.bag_size来存储word_count_struct。