我具有结构t_REC_instance,我想创建一个实例并为其变量分配内存。我做错了。在注释的空间中,调试时会出现sigINT错误。有人可以指出我在做什么错。c
typedef struct sAppRecipe
{
union
{
struct sAppBread
{
int sugar_qty;
int salt_qty;
}tAppBread;
struct sAppPancake
{
int sugar_qty1;
}tAppPancake;
};
}tAppRecipe;
typedef struct sAppRecipe tAppRecipe;
struct sREC_instance
{
tAppRecipe *currentRecipe;
tAppRecipe *newRecipe;
tAppRecipe *updateRecipe;
};
typedef struct sREC_instance t_REC_instance;
tAppRecipe *REC_Alloc(void) {
return malloc(sizeof (tAppRecipe));
}
t_REC_instance *instance; //
int REC_createInstance1(t_REC_instance *instance)
{
instance->currentRecipe =REC_Alloc(); // there is a problem here
if (!instance->currentRecipe)
{
printf("not allocated");
}
}
void main()
{
REC_createInstance1(instance);
}
行
instance->currentRecipe =REC_Alloc();
是一个问题,因为您正在访问不存在的currentRecipe
的instance
成员; instance
没有指向任何地方,因此您需要先分配它:
instance = malloc(sizeof(t_REC_instance));
修复:
您的代码正在分配currentRecipe
所指向的结构的instance
成员,但是instance
未设置为任何东西,这意味着它指向了导致错误的内存的某些无效部分。
更改此行:
t_REC_instance *instance;
to
t_REC_instance instance;
和此行:
REC_createInstance1(instance);
to
REC_createInstance1(&instance);