当我尝试删除从Queue获取的结构时,它会抛出运行时堆错误。
这是我的样本。
/* "Message_content" structure hold the content of message and body. */
typedef struct msgContent
{
char *message;
char *body;
struct msgContent *nextptr;
}Message_content;
static Message_content *frontptr;
static Message_content *rearptr;
Message_content* msgContent;
msgContent = QueueDelete();
free(msgContent); //**error happens while calling this function**.
这是我在c。
中的QueueDelete()函数static Message_content* QueueDelete()
{
Message_content *tempMsgContent = NULL;
if(frontptr == NULL)
{
}
else if(frontptr==rearptr)
{
tempMsgContent = frontptr;
tempMsgContent->nextptr = NULL;
frontptr = rearptr = NULL;
}
else
{
tempMsgContent = frontptr;
frontptr = frontptr->nextptr;
tempMsgContent->nextptr = NULL; // rectify the problem said by philong
}
return tempMsgContent;
}
修改 添加队列插入函数,它将为我的代码赋予意义。
这是c
中的队列插入功能 static int QueueInsert(char *message ,char *body)
{
Message_content *tempMsgContent = (Message_content*) malloc(sizeof(Message_content*));
if(rearptr == NULL && frontptr == NULL)
{
rearptr = tempMsgContent;
rearptr->message = message;
rearptr->body = body;
rearptr->nextptr=NULL;
frontptr = rearptr;
return 1;
}
rearptr->nextptr = tempMsgContent;
rearptr = rearptr->nextptr;
rearptr->body = body;
rearptr->message = message;
rearptr->nextptr = NULL;
return 1;
}
答案 0 :(得分:3)
这可能是你的问题:
tempMsgContent = frontptr;
tempMsgContent->nextptr = NULL;
frontptr = frontptr->nextptr;
您将nextptr
的{{1}}设置为tempMsgContent
,这很好,但NULL
和frontptr
仍然指向相同的内存位置!
在更改tempMsgContent
之后将nextptr
设置为NULL
。
修改检查frontptr
代码,我看到这一行:
QueueInsert
它的作用是为指针(Message_content *tempMsgContent = (Message_content*) malloc(sizeof(Message_content*));
)分配足够的内存!您应该使用没有星号的sizeof(Message_Content*)
。这肯定会弄乱你的堆!