Reputation: 2070
I'm having some trouble getting my program to work. It's supposed to be a dirt simple program that simulates the ready queue on an operating system. It uses priority Queues to store process objects (called PCBs), and a PCB pointer called CPU to keep track of which process is in the CPU. The point of the program is that it is supposed to recycle PCBs without destroying them.
The problem I am having is that when I dequeue a PCB and assign it to a pointer, I receive this error:
error: taking address of temporary [-fpermissive]
This is what the code looks like:
void OSSim::createProcess(){
PCB * newP;
if(unusedPCBs.isEmpty()) //unusedPCBs is a priorityQueue
newP = new PCB();
else{
newP = &(unusedPCBs.dequeue()); // THIS LINE IS CAUSING THE ERROR
}
newP->PID = pidCounter;
pidCounter++;
std::cout << "Process ID " << newP->PID << " created";
if(CPU == 0){
CPU = newP;
std::cout << " and moved to CPU\n";
} else {
readyQueue.enqueue(*newP);
std::cout << " and moved to the Ready Queue\n";
}
}
So I searched StackOverflow and found a solution, which is to create a temporary new PCB (from the one being dequeued) and take have the pointer point to that instead:
void OSSim::createProcess(){
PCB * newP;
PCB temp;
if(unusedPCBs.isEmpty()) //unusedPCBs is a priorityQueue
newP = new PCB();
else{
temp = unusedPCBs.dequeue(); // THE "FIX"
newP = &temp;
}
newP->PID = pidCounter;
pidCounter++;
std::cout << "Process ID " << newP->PID << " created";
if(CPU == 0){
CPU = newP;
std::cout << " and moved to CPU\n";
} else {
readyQueue.enqueue(*newP);
std::cout << " and moved to the Ready Queue\n";
}
}
However the problem with this is that the pointer is pointing to a PCB object which was created locally, and so it disappears once the function ends. When I try to reference that same PCB later, I see that the data it was holding had been corrupted.
So I feel like I'm in a catch-22. My goal is to re-use the PCB object after it is dequeued without destroying it and creating a new one. When I try to capture it with a pointer I get an "address of temporary" error, and when I try to capture it by temporarily creating a new PCB object to store it, that object is declared locally and is destroyed once the routine ends.
Any advice would be greatly appreciated. Thank you so, so much.
Also, here is my dequeue() function:
template <typename T>
T PriorityQueue<T>::dequeue(){
if(isEmpty()){
std::cout << "\n\nWARNING: Trying to dequeue empty queue\n\n";
throw 3;
} else {
Node * frontNode = head;
T result = frontNode -> data;
if(size == 1){
head = 0;
tail = 0;
} else {
head = frontNode -> prev;
head -> next = 0;
}
delete frontNode;
size--;
return result;
}
}
Upvotes: 0
Views: 154
Reputation: 63
Copy construct a new PCB on the heap.
if(unusedPCBs.isEmpty())
newP = new PCB();
else{
newP = new PCB( unusedPCBs.dequeue() );
}
Upvotes: 2