-
Linked list logic error
Hi, their is part of a homework problem which I seem to be stuck on. It asks what are the logic errors in a program if the function defined is supposed to return the legnth of a linked list.
The function is:
Code:
int length(NodePtr *Head){
int size = 0;
NodePtr *cur;
while(cur != NULL){
size++;
cur = cur->next;
}
}
I am having trouble seeing what is wrong with it...It seems as it is set to increment the int variable size by one while the pointed variable cur is not null. cur is then set to be the next value. This would continue until cur had nothing left thus making it null and stopping the while loop.
Help please!
-
>> NodePtr *cur;
hint: what does this point to?
-
to the node counter?
..nvm, let me think some more before answering.
-
regardless of the data type, a variable should be initialized to a valid state before working with it. consider:
Code:
int
main(void)
{
int i;
cout << i << endl;
}
what do you think the program will print?
-
whatever random value the os has stored in that memory space for i at that time. Other compiler would just give an error.
-
-
And this is the exact question if I asked it wrong:
Code:
The following function is supposed to return the length of a linked list. What are the logical errors in
this function?
int length(NodePtr *Head){
int size = 0;
NodePtr *cur;
while(cur != NULL){
size++;
cur = cur->next;
}
}
-
Oh, so you are saying since *cur is pointing to nothing, it cant work?
-
I believe it assumes that elsewhere NodePtr and Head, etc are defined.
-
It's an uninitialized pointer. It doesn't matter if those things are defined elsewhere, cur doesn't point to anything when it is first used.
>> Other compiler would just give an error.
No, it is not a compile error, it is a logical error. All compilers should probably give a warning, though.
-