gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 00:18:06 24 4
gpt4 key购买 nike

我有一个结构,其中包含 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com