我尝试实现一个包含任务控制块(TCB)的双向链表,每个包含一个指向函数的指针和一个void指针。我运行我的程序而不使用循环,它正常工作。但是,当我使用for循环时,它会停止工作。我的计划如下:
#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;
}
我的计划有什么问题?
答案 0 :(得分:2)
Queue *q;
你的队列指向垃圾内存地址,你需要实例化一个对象:
Queue *q = new Queue();
或更好,将其分配到堆栈
Queue q;