1

静的配列があり、関数内でループ内に新しい構造体を作成し、それを配列内の各インデックスに割り当てます。関数では値を確認できますが、別の関数では配列値のジャンクが表示されます。このようなものに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;
}
4

1 に答える 1

2

コードには2つの問題があります。

問題1:

構造体new_struct自体はスタック上にあり、関数のスコープが終了すると割り当てが解除されます。したがって、配列要素が関数のスコープを超えて指しているのは、存在しないもの、つまりガベージです。

解決策:
スコープを超えてアクセスするには、構造体がヒープメモリ上に存在する必要があります。


問題2:

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

関数に渡されるポインターの浅いコピーを作成しますadd_to_filetype_table()。例から、関数に渡されるポインターの所有者とその存続期間は明確ではありません。呼び出す前にこれらのポインターの割り当てが解除されるとget_table_value()、グローバル静的構造が残ります。ダングリングポインタを使用するため、出力時にガベージ値を取得します。

解決:

渡されるポインタのディープコピーを作成する必要があります。
構造体メンバーにメモリをstrcpy()割り当ててから、割り当てられたメモリに文字列をcopy()します。

于 2012-05-03T04:16:46.163 に答える