C 将结构分配给静态数组

C 将结构分配给静态数组,c,C,我有一个静态数组,在一个函数中,我在循环中创建一个新结构,并将其分配给数组中的每个索引。在函数中,我可以看到值,但在另一个函数中,我看到数组值的垃圾。我必须用malloc来做这样的事情吗 struct file_types { char * typename; char * MIMEtype; }; static struct file_types *file_type_table; //Table of parameters static int file_type_tabl

我有一个静态数组,在一个函数中,我在循环中创建一个新结构,并将其分配给数组中的每个索引。在函数中,我可以看到值,但在另一个函数中,我看到数组值的垃圾。我必须用malloc来做这样的事情吗

struct file_types
{
    char * typename;
    char * MIMEtype;
};

static struct file_types *file_type_table; //Table of parameters
static int file_type_table_num=0;

int add_to_filetype_table(char *param, int param_len, char *value, int val_len, char* value2)
{   if ((param == NULL) || (value==NULL) || (value2 == NULL))
        return 0;
    if ((strcmp(param,"type") != 0) || (strcmp(value,"") == 0) || (strcmp(value2,"") == 0))
        return 0;

    if (file_type_table==NULL)
        file_type_table =   emalloc(sizeof(struct file_types));
    else
        file_type_table =  erealloc(file_type_table, (file_type_table_num*sizeof(struct file_types)+ sizeof(struct file_types)));

    file_type_table_num += 1;
    int index = file_type_table_num -1;

    struct file_types new_struct;
    new_struct.typename = value;
    new_struct.MIMEtype = value2;

    file_type_table[index] = new_struct;

    return 1;
}
此处访问结构时出现问题:

char* get_table_value(char * key)
{   logg("In get_table_value");
    int i;

    char* value;

    for (i=0;i<file_type_table_num;i++)
    {   
        if (strcmp(((file_type_table)[i]).typename, key) == 0)
        {   
            return (file_type_table[i]).MIMEtype;
        }
    }
    return value;
}
char*获取表值(char*键)
{logg(“在get_表_值中”);
int i;
字符*值;

对于(i=0;i,代码中有两个问题:

问题1:

new_struct.typename = value;
new_struct.MIMEtype = value2;
结构
new\u struct
本身位于堆栈上,一旦函数范围结束,它就会被释放,因此数组元素指向函数范围之外的东西是不存在的,也就是垃圾

解决方案:
该结构需要驻留在堆内存中,才能在范围之外进行访问


问题2:

new_struct.typename = value;
new_struct.MIMEtype = value2;
创建传递给函数
add_to_filetype_table()
的指针的浅层副本,从示例中不清楚谁拥有传递给函数的指针&如果在调用
get_table_value()之前解除分配这些指针,它们的生存期是什么
然后,您的全局静态结构留下了悬空指针,因此您在输出它们时会得到垃圾值

解决方案:

new_struct.typename = value;
new_struct.MIMEtype = value2;
您需要对传递的指针进行深度复制。

将内存分配给结构成员,然后将(
strcpy()
)字符串复制到分配的内存中。

我处理了新的结构(struct file_types*new_struct=emalloc(sizeof(struct file_types))),但在执行strcpy(new_struct->typename,value)时会出现分段错误。如果我只执行“=”然后我仍然有原来的问题。@user994165:您需要
malloc
结构指针成员(
typename
&
MIMEtype
)同样!如果只为结构指针而不是指针成员分配内存,那么结构成员没有足够的内存来保存使用
strcpy
复制的字符串。