Reputation: 55
First off I am brand new to C and have been thrown into a program in which I must use C. Now I believe my problem has something to do with a pointer, but when I try to print the list (to make sure I have stored it in the correct order my program crashes after the second time through the loop.
This is my insert function which inserts by the lowest time needed, and I believe it is right but have not been able to test it as my print crashes
void insertProcess(Process& process, Process* &head, Process* curr, Process* prev){
curr = head;
if(head == NULL){
head = &process;
}
else{
prev = head;
while(process.timeNeeded > curr->timeNeeded){
prev = curr;
curr = curr->next;
}
prev->next = &process;
process.next = curr;
}
}
Here is my simple loop which should print the list. This will run a few times before giving an a 'access violation reading location'
while(curr->next != NULL){
printf("%s %i %i %i\n", process.processName, process.arrivalTime, process.timeNeeded, process.priority);
curr = curr->next;
}
I am pretty sure the error would be in one of these segments of code, I would appreciate any help.
EDIT: OK with the help of the first poster I fixed the original problem, but now I have an infinite loop when printing. I am pretty sure it would be because I am inserting in order and never set a NULL pointer after the last item. Does that seem correct, and if so, is there any way to fix it? Thanks again
Upvotes: 3
Views: 436
Reputation: 1
You should learn how to use a debugger. On Linux you should compile with both -g
(to get debugging information produced by the compiler) and -Wall
(to get all warnings) passed to gcc
or g++
. Then you can use the gdb
debugger on your executable.
Upvotes: 0
Reputation: 114481
In your function you are passing a Process
by value and this means that the function will work on a local copy of the Process
object that will be destroyed when the function exits.
Your code however is linking in this local copy and therefore once you exit the function your linked list is now using a Process
object that has been already destroyed.
Another problem is that when looping to search the insertion point you are not considering the case that the inserted process may be the last one and in that case curr
will become NULL in the loop.
Upvotes: 2