Reputation: 25
I try to implement a doubly linked-list that holds task control blocks (TCBs), each of which contains a pointer to function and a void pointer. I run my program without using loop and it works properly. However, when I use a for loop, it stops working. My program is as follows:
#include <iostream>
#include <stdlib.h>
using namespace std;
class TCB {
public:
void *data;
TCB *next;
TCB *prev;
public:
void (*myTask)(void *);
};
typedef void (*task)(void *data);
class Queue {
public:
TCB *head;
TCB *tail;
int numberOfElenments;
public:
void QueueInsert(void *data, task myTask);
void QueueRemove(TCB *task);
};
// Insert at tail
void Queue::QueueInsert(void *value, task myTask)
{
TCB *newTask = (TCB*)calloc(1, sizeof(TCB));
newTask->data = value;
newTask->myTask = myTask;
if(head == NULL) {
head = newTask;
tail = newTask;
} else {
tail->next = newTask;
newTask->prev = tail;
tail = newTask;
}
numberOfElenments++;
}
// Remove a particular node in queue
void Queue::QueueRemove(TCB *task)
{
if(head == NULL) {
// do nothing
}
if(task == head && task == tail) {
head = NULL;
tail = NULL;
} else if(task == head) {
head = task->next;
head->prev = NULL;
} else if(task == tail) {
tail = task->prev;
tail->next = NULL;
} else {
TCB *after = task->next;
TCB *before = task->prev;
after->prev = before;
before->next = after;
}
numberOfElenments--;
free(task);
}
void foo(void *data) {
cout<<"Hello world!"<<endl;
}
void foo2(void *data) {
cout<<"Hello, I am foo2!"<<endl;
}
int main(){
Queue *q;
q->QueueInsert(NULL, foo);
q->QueueInsert(NULL, foo2);
TCB *task;
task = q->head;
for(int i = 0; i < 2; i++) {
task->myTask(task->data);
task = task->next;
}
return 0;
}
What is wrong with my program?
Upvotes: 0
Views: 56
Reputation: 26476
Queue *q;
your Queue points to garbage memory address, you need to instantiate an object :
Queue *q = new Queue();
or better, allocate it on the stack
Queue q;
Upvotes: 2