정적 배열이 있고 함수에서 루프에 새 구조체를 만들고 배열의 각 인덱스에 할당합니다. 함수에서 값을 볼 수 있지만 다른 함수에서는 배열 값에 대한 정크가 보입니다. 이런 식으로 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;
}
new_struct (struct file_types * new_struct = emalloc (sizeof (struct file_types));)를 malloc했지만 strcpy (new_struct-> typename, value)를 수행 할 때 세그먼트 화 오류가 발생합니다. "="만하면 원래 문제가 남아 있습니다. – user994165
@ user994165 : 구조체 포인터 멤버 ('typename'과'MIMEtype')를'malloc'해야합니다! 포인터 멤버가 아닌 포인터를 구조체에 할당하면 구조체 멤버는'strcpy'를 사용하여 복사 한 문자열을 저장할 수있는 메모리가 부족합니다. –