C - 我的内存释放功能有什么问题?

标签 c pointers memory-management struct free

我有一个结构,其中包含 2 个整数和一个指向另一个结构的指针。我首先为结构分配内存,然后为指针分配内存。当我释放内存时,我首先释放指针,然后释放结构。

当我运行我的程序并调用释放内存的函数时,它会在调用时崩溃。当我不调用释放内存的函数时,它工作正常,但我没有释放内存。

我尝试删除释放分配给指针的内存的行并且程序没有崩溃,但我认为那是不对的,因为每个“malloc/calloc”都需要一个“free”,对吗?有人看到释放功能有什么问题吗?

//Define a struct data type
struct q_element
{
    //Declaration of struct members
    int element;
    int priority;
    struct q_element *next_element;
};

//Method to allocate memory
struct q_element* allocateStruct()
{
    //Declaration of a variable
    struct q_element *e;

    //Allocate memory for one queue element
    e = malloc(sizeof(struct q_element));

    //Allocate memory for one pointer to a queue element
    e->next_element = calloc(1,sizeof(struct q_element*));

    //Initialize integer members of queue element
    e->element = 0;
    e->priority = 0;

    return e;
}

//Method to free memory allocated
void freeStruct(struct q_element* e)
{
    //Free up pointer member
    free(e->next_element);

    //Free up struct
    free(e);
}

最佳答案

您不需要为 next_element 指针分配内存。指针已经存在,例如 int element

因此,如果您只想分配一个元素,可以将 next_element 指针设置为 NULL,一切都很好。

关于C - 我的内存释放功能有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29018485/

相关文章:

c++ - 接受指针数组的输入

c - C 中的斐波那契数列 - 直到给定数字的数字序列

c++ - Makefile 编译 c 和 cpp 文件

c - Queue Implementation using two stacks-指针不兼容错误

c - 使用循环为指针赋值

将 NULL 强制转换为 C 中的结构指针?

c - 使用指针时将二维数组用作多个一维数组

c++ - 通过一次调用 new 运算符来批量分配对象?

c# - 如何增加分配的内存? {由于内存不足异常,函数评估被禁用。}

c - 在 C 中监视外部进程的读/写事件?