【发布时间】:2023-04-02 10:17:01
【问题描述】:
#include <stdio.h> /* the "QueueTypes.h" file, */
#include <stdlib.h> /* given above on lines 1:15, is */
#include "QueueImplementation.c"
void main(void){
Queue *que;
ItemType *num;
num = 0;
InitializeQueue(que);
int count = 0;
int check;
int i;
if(Empty(que) != 1){
count = count + 1;
}
printf("%d", count); <- segmentation fault
if(Remove(que, num) != 0){
count = count + 1; <- segmentation fault
}
这些是程序中不断出现分段错误的部分。我是否非法访问任何东西?
这是 queueimplementation.c。当我删除被指出的行时,程序运行正常并正常返回错误。
/* ------------< begin file "QueueImplementation.c" >------------ */
#include <stdio.h> /* the "QueueTypes.h" file, */
#include <stdlib.h> /* given above on lines 1:15, is */
#include "QueueInterface.h" /* included in "QueueInterface.h" */
/* on line 3 of Program 7.4. */
void SystemError(char *errorMsg) {fprintf(stderr,errorMsg);}
void InitializeQueue(Queue *Q)
{
Q->Front = NULL;
Q->Rear = NULL;
}
/* -------------------- */
int Empty(Queue *Q)
{
return (Q->Front == NULL);
}
/* -------------------- */
int Full(Queue *Q)
{ /* we assume an already constructed queue, Q, is */
return 0; /* not full, since it could potentially grow */
} /* as a linked structure */
/* -------------------- */
int Insert(ItemType R, Queue *Q)
{
QueueNode *Temp;
/* attempt to allocate */
Temp = (QueueNode *) malloc(sizeof(QueueNode)); /* a new node */
if (Temp == NULL) { /* Temp = NULL signals allocation */
SystemError("system storage is exhausted"); /* failure */
return 0;
} else {
Temp->Item = R;
Temp->Link = NULL;
if ( Q->Rear == NULL ) {
Q->Front = Temp;
Q->Rear = Temp;
} else {
Q->Rear->Link = Temp;
Q->Rear = Temp;
}
}
return 1;
}
/* -------------------- */
int Remove(Queue *Q, ItemType *F)
{
QueueNode *Temp;
if (Q->Front == NULL) {
SystemError("attempt to remove item from empty Queue");
return 0 ;
} else {
*F = Q->Front->Item;
Temp = Q->Front;
Q->Front = Temp->Link;
free(Temp);
if (Q->Front == NULL) Q->Rear = NULL;
return 1;
}
}
/* -------------------- */
【问题讨论】:
-
我怀疑是那些行导致了段错误。能否提供
QueueImplementation.c的实现? -
您的分段错误没有发生在
printf()或增加count整数时。最可能的问题是你还没有理解QueueImplementation.c中发生了什么。 -
我将在其中添加 QueueImplementation.c,但是当我删除这些行时程序运行良好
-
出现异常的原因是
que指针未初始化。查找“按值传递”以获得解释。 -
永远不要
#include实现(又名“.c”)文件!