|
-
November 15th, 2009, 11:13 AM
#1
Segmentation Fault (sometimes)
I'm trying to build a simple search function on an array of linked lists that compares values from another array. When I run it six out of ten times I get a segmentation fault. Since this is the first time I've used linked lists in this way, I'm curious why it would work sometimes and not others. Any help would be appreciated.
Code:
for (idx = 0; idx < SEARCH_MAX; idx++) {
total += count;
count = 0;
count++;
while (nodeArray[address]->value != searchArray[idx] && nodeArray[address]->value != 0) {
if (nodeArray[address]->link != NULL) {
nodeArray[address] = nodeArray[address]->link;
} else {
nodeArray[address]++;
}
count++;
}
}
-
November 15th, 2009, 12:11 PM
#2
Re: Segmentation Fault (sometimes)
It's not easy to give advice without seing the impelementation of your linked list (as you are not using std::list), but here is one: A search function should not modify the linked list array it is searching in. Your code below does at two points. Try passing in your linked list array as const and it will not compile any more.
More computing sins are committed in the name of efficiency (without necessarily achieving it) than for any other single reason - including blind stupidity. --W.A.Wulf
Premature optimization is the root of all evil --Donald E. Knuth
Please read Information on posting before posting, especially the info on using [code] tags.
-
November 15th, 2009, 08:55 PM
#3
Re: Segmentation Fault (sometimes)
 Originally Posted by reubenpatterson
I'm curious why it would work sometimes and not others.
I'm going to assume that your code is deterministic (no random numbers no threading) and should in theory be the same every time.
If its crashing some times and not others this can be caused by pointers not being set. Like any variable, pointers will contain the value of whatever their memory happened to contain until you change it. It is possible that an uninitialized pointer could some times point to memory that actually exists. Especially if your code has just deleted a similar object, a new object may occupy the same memory as an old one and (without initialisation) point to whatever the old one did. This behaviour could easily be random. Such errors are usually amongst the hardest to track.
Signature
Please use: [ code ][/ code ] tags and reasonably correct tabbing. They really help us read your code
End Signature
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|