首页 > 解决方案 > C中的struct和free()

问题描述

每当我插入一个新值时,我的数据都会被覆盖,如果我在主程序中省略了我的 free(),我的程序工作正常。为什么?如何纠正这个问题。结构的内存分配是否正确?

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct List
{
        char val[20] ;
};

struct Hashtable
{
            struct List *start;
};
struct Hashtable ht[26];

void init();
void insert(struct List*);
void init()
{
        register int j;
        for (j=0;j<26;j++)
        {
           ht[j].start=NULL;
        }
}
int main(void)
{
        init();
        int i=0;
        for (int i=0;i<5;i++)
        {
        struct List *newnode=(struct List*)malloc(sizeof(struct List));
        scanf("%s",newnode->val);
        insert(newnode);
        free(newnode);
        newnode=NULL;
        }
        return 0;
}

void insert(struct List *node)
{

        if ( ht[node->val[0]-97].start==NULL)
        {
                ht[node->val[0]-97].start=node;
                return;
        }
        else
        {
                printf("The value is %s\n", ht[node->val[0]-97].start->val);
        }


}

-------------------------------------------------- -------------------------------------------------- --------------------------------------------- ___________________________________________________________________________

标签: cstruct

解决方案


当您分配指针时,您只复制指针本身,而不是它们可能指向的内存。

当您free使用指针调用时,该指针的所有副本都将变为无效并且不能再使用。

您要么需要在函数中创建一个全新的副本insert(包括分配新List结构),要么不应该调用free.


我个人的建议是您根本不在main函数中进行分配,并且该insert函数将字符串作为参数“插入”(而不是List当前使用的指针)。

也许是这样的:

void insert(char *val)
{
    // Get the hash-table index (note that it only works with ASCII encoding)
    char hash = tolower(val[0]) - 'a';

    // First check if it exists
    if (ht[hash].start == NULL)
    {
        // No, then add it

        // First allocate memory for the node
        struct List *node = malloc(sizeof *node);

        // Then copy the string
        strcpy(node->val, val);

        // And finally add it
        ht[hash].start = node;
    }
}

那么你在main函数中的循环可能就像

for (unsigned i = 0; i < 5; ++i)
{
    char val[20];
    scanf("%19s", val);
    insert(val);
}

推荐阅读