how to remove this segmentation fault
hi guyz .. i have written this program ascll.list that forms a linked list in ascending order...... the programs works fine on turboc 3 on windows bt gives segmentation fault on gcc4.3.1 on fedora 9
PHP Code:
PHP Code:
|
Why dont you run it thru a debugger like gdb yourself and find out why its happening. You havent even shown where in your program the segfault occurs.
|
i did it man.... its the if condition in the while loop.... in add function... but the logic seems 2 b correct...as program works fyn on windows
trouble is in if(temp->data<=num && ((temp->link)->data>num || temp->link==NULL)) |
Quote:
What happens when temp->link==NULL ?? Quote:
|
I would recommend that you augment this code in add():
Code:
struct node *temp,*r; Code:
r->link = NULL; Code:
if(temp->data<=num && ((temp->link)->data>num || temp->link==NULL)) Code:
void add(struct Node** head, int num) |
I'm confident my earlier post is the answer author_unknown should look at. I hope the subsequent discussion doesn't hide that.
Quote:
Maybe it is good practice to initialize such pointers immediately when allocated, even when that initialization is reliably over written by subsequent code. Certainly that practice would avoid a lot of beginner mistakes. Personally, I hate adding wasted steps to code. I often leave out such initialization and usually put in a comment explaining why I'm sure it is safe to leave out a particular initialization. Quote:
I don't think that is a good idea. (oops, I failed to resist this time). I think it is better to explain the specific issues in the code given. In this case, I just explained the bug that caused the segment fault. I could explain why many other details in the code are bad practice. But for the question asked in this thread, I guessed it would be best to just explain the bug itself. But, while we're on the subject of clean rewrites, one problem in the original and just as bad in your version is too many possible paths. For a problem this simple, you shouldn't need all the exception cases coded that way. They make it too hard to desk check the logic and see that all paths are valid. It is better to write the main path with enough generality that it covers all cases. The key to that in the add function is a Node** that is always valid and becomes the place you put the pointer to the new node and whose successor becomes the successor to the new node. Code:
void add(struct Node** head, int num) Code:
void add(struct Node** head, int num) |
All times are GMT -5. The time now is 09:39 PM. |