【问题标题】:Problem in allocating memory for structure pointer为结构指针分配内存的问题
【发布时间】:2020-03-08 15:40:21
【问题描述】:

我有结构 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);
}

【问题讨论】:

    标签: c pointers structure procedural-programming


    【解决方案1】:

    线

    instance->currentRecipe =REC_Alloc();

    是一个问题,因为您正在访问不存在的instancecurrentRecipe 成员; instance 没有指向任何地方,所以你需要先分配它:

    instance = malloc(sizeof(t_REC_instance));

    【讨论】:

    • 嗨@Reticulated Spline,我需要更多帮助。我想在这里理解指针。我正在调用 REC_DestroyInstance(instance);创建后,当我进入函数时,我没有看到 REC_CreateInstance(instance); 分配的内存地址; .即 REC_DestroyInstance(instance) 函数中的实例地址是 0x00 而不是创建的地址?该地址会在整个程序中不可用吗?
    • @madhumadi 请创建另一个问题,因为这是一个单独的问题。
    【解决方案2】:

    修复:

    您的代码正在分配instance 指向的结构的currentRecipe 成员,但instance 未设置任何内容,这意味着它指向导致错误的内存的某些无效部分。

    改变这一行:

    t_REC_instance *instance;
    

    t_REC_instance instance;
    

    还有这一行:

    REC_createInstance1(instance);
    

    REC_createInstance1(&instance);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-09-23
      • 1970-01-01
      • 2023-04-02
      • 2017-01-03
      • 1970-01-01
      • 1970-01-01
      • 2021-12-26
      • 2019-06-29
      相关资源
      最近更新 更多