You can't comment malloc-line in insert function. The use of malloc()
is for allocate new memory dynamically for new nodes to insert in linked-list.
Read: void* malloc (size_t size);
Allocate memory block
Allocates a block of size bytes of memory, returning a pointer to the beginning of the block.
So suppose if you comment/remove malloc line in insert()
(read comment):
//struct node *root= malloc(sizeof(struct node ));
root->key = data; // here illegal operation
root->left = NULL; // here illegal operation
root->right = NULL; // here illegal operation
then root
value will be garbage and you are access and perform read/write action on garbage address not allocated by the process - an memory illegal operation.
Your code will compile because syntax-wise the code is correct but at runtime the OS will detect illegal memory access and can terminate your code. (interesting to note: as OS detects memory right violation by a process -- An invalid access to valid memory gives: SIGSEGV And access to an invalid address gives: SIGBUS). --Actually this cause Undefined behavior. In the worst case your program may seem execute without any failure, producing garbage results.
it gives me a segmentation fault after taking the first value. what is going on here?
As I explained above removing malloc()
makes your program behaving in Undefined manner(read: Undefined behaviour). If program runs as Undefined behavior you can's guess what can be happen, in worst case your program may execute without any failure, or may be run partial (that is what you are observing). Thing is that when OS detects illegal memory access and send a signal to terminate the process. (may be first five random-garbage value to root
points to a memory associated with our program and according to OS access to that memory is not a illegal operator - while for fifth time random value of root
is a memory that doesn't belong to the process and read/write operation on that memory detected by OS hence your code finally terminate with segmentation fault).