I made a code in which malloc()
is called, but it is returning a null pointer. When I call the same malloc()
in main()
and pass to the function, it is working totally fine. So please tell me what is the problem.
Here is my code. I am having problems with the malloc()
in the function reverse()
. The malloc()
s in other functions are working fine. So why is there problem with the one in that function. I have enough memory in my computer, so that's definitely not the problem.
#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;
}
malloc
s here. Which one returns 0?malloc
returnsNULL
if you are not checking it? In generalmalloc
returnsNULL
if there is no more memory left.