Gam*_*tro 1 c malloc queue stack
我做了一个malloc()调用的代码,但它返回一个空指针.当我调用相同malloc()的main()并传递给函数时,它工作得很好.请告诉我这是什么问题.
这是我的代码.我malloc()在函数中遇到问题reverse().malloc()其他功能中的s工作正常.那么为什么那个函数中存在问题呢?我的电脑里有足够的内存,所以绝对不是问题所在.
#include <stdio.h>
#include <stdlib.h>
typedef struct node
{
int data;
struct node *next;
} SNode;
typedef struct
{
int count;
SNode *top;
} Stack;
int isSEmpty(Stack *s)
{
return (s->count==0);
}
void push(Stack *s, int x)
{
SNode *temp = (SNode *)malloc(sizeof(SNode));
temp->data = x;
temp->next = s->top;
s->top = temp;
s->count++;
}
int pop(Stack *s)
{
if (isSEmpty(s))
{
printf("Underflow");
return -1;
}
SNode *temp = s->top;
s->top = s->top->next;
int t = temp->data;
free(temp);
s->count--;
return t;
}
typedef struct qnode
{
int data;
struct qnode *next, *prev;
} QNode;
typedef struct
{
QNode *front, *rear;
int count;
} Queue;
int isQEmpty(Queue *q)
{
return (q->count==0);
}
void enQueue(Queue *q, int x)
{
QNode *temp = (QNode *)malloc(sizeof(QNode));
temp->data = x;
temp->prev=q->rear;
temp->next = NULL;
q->rear->next = temp;
q->rear = temp;
q->count++;
if (q->count==1)
{
q->front = q->rear;
}
}
int deQueue(Queue *q)
{
if (isQEmpty(q))
{
printf("Underflow");
return -1;
}
QNode *temp = q->front;
q->front = q->front->next;
int t = temp->data;
free(temp);
q->count--;
return t;
}
void reverse(Queue *q)
{
Stack *s = (Stack *)malloc(sizeof(Stack));
s->count = 0;
while (!isQEmpty(q))
{
push(s, deQueue(q));
}
while (!isSEmpty(s))
{
enQueue(q, pop(s));
}
}
int main()
{
char p = 'y';
Queue *q = (Queue *)malloc(sizeof(Queue));
q->count = 0;
while (p =='y')
{
printf("Enter data to be Enqueued: ");
int d;
scanf("%d", &d);
enQueue(q, d);
printf("Do you want to enter more data? y/n:");
scanf(" %c", &p);
}
printf("Original queue Front: %d Rear: %d\n", q->front->data, q->rear->data);
reverse(q);
printf("Reversed queue Front: %d Rear: %d", q->front->data, q->rear->data);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
你的程序几乎没有内存耗尽,这就是为什么malloc()会返回NULL.相反,糟糕的编程风格和凌乱的代码的组合导致与未初始化的内存的访问相关的问题,这是未定义的行为,一旦触发UB,就无法再预测程序的行为了.
你需要解决的第一件事是避免这种结构
q->rear->next = temp;
Run Code Online (Sandbox Code Playgroud)
因为q->rear可能是因为NULL如果你取消引用它你会调用UB.
然后你需要显式地初始化结构的成员,malloc()只为你分配内存,它不做任何初始化,一个好的方法是创建一个分配和初始化空实例的函数,如下所示
Queue *queue_new(int count)
{
Queue *queue;
queue = malloc(sizeof(*queue));
if (queue == NULL)
return NULL;
queue->count = count;
queue->front = NULL;
queue->rear = NULL;
return queue;
}
Run Code Online (Sandbox Code Playgroud)
另外,不要将声明与代码混合.我必须搜索Queue编写上述函数的定义,并且我使用代码编辑器的查找/替换功能.
将所有结构和类型定义放在所有代码之上,以便于查找其中任何一个.
| 归档时间: |
|
| 查看次数: |
416 次 |
| 最近记录: |