Reputation: 45
This program is supposed to make a random linked list of n
numbers that the user inputs, but when it tries to print the linked list it gets a segmentation fault.
The program works until it has to display the linked list.
#include <iostream>
class node
{
public:
// TYPEDEF
typedef double value_type;
// CONSTRUCTOR
node(
const value_type& init_data = value_type(),
node* init_link = NULL
)
{ data_field = init_data; link_field = init_link; }
// Member functions to set the data and link fields:
void set_data(const value_type& new_data) { data_field = new_data; }
void set_link(node* new_link) { link_field = new_link; }
// Constant member function to retrieve the data:
value_type data() const { return data_field; }
// Constant member functions to retreive the link:
node* linker() const { return link_field; }
private:
value_type data_field;
node* link_field;
};
int myrand(int)
{
return(1 + rand() %(1000 - 1 +1));
}
void print_linked_list(node*& head_ptr, node*& print_ptr, size_t n)
{
for (size_t i =1 ; i <= n ; i++) {
head_ptr = new node(myrand(n), head_ptr);
}
std::cout << "Unsorted List: " << std::endl;
for (print_ptr = head_ptr; print_ptr !=NULL; print_ptr = print_ptr->linker()) {
std::cout << print_ptr->data() << " ";
}
}
int main()
{
size_t n;
srand(time(NULL));
node* head_ptr;
node* print_ptr;
std::cout << "Please input a number" << std::endl;
std::cin >> n;
print_linked_list(head_ptr, print_ptr, n);
return 0;
}
Upvotes: 3
Views: 46
Reputation: 118300
head_ptr is not initialized to NULL
.
As such, the first node that gets created will get a garbage pointer for its link_field
.
As such, when your print code attempts to walk the link list, it will eventually hit the garbage pointer, and go waltzing off into never-never land.
Upvotes: 3
Reputation: 980
You are trying to access an uninitialized pointer. You give the print_linked_list
function the head_ptr
variable, which is uninitialized. It then uses that value as the pointer to the next node when creating the first node. This means the condition print_ptr != NULL
is never met.
This can be fixed by setting head_ptr
to NULL
when you declare it in main
.
Upvotes: 3