Well one problem is you're not typecasting your pointer.
The line:
b=malloc(sizeof(b));
Should be:
b=(bst*)malloc(sizeof(b));
Your code gives me an error when I compile it in gcc.
This is how to identify and fix errors in the future:
Testing in GDB:
Full code:
#include <malloc.h>
#include <stdio.h>
typedef struct node
{
struct node *leftChild, *rightChild;
int value;
} bst;
void insert(bst* b, int i)
{
b=(bst*)malloc(sizeof(b));
b->value=i;
b->leftChild = NULL;
b->rightChild = NULL;
printf("[%i]",b->value);
return;
}
main()
{
bst* b;
insert(b,5);
printf("[%i]",b->value);
}
Compiled with
%g++ -g main.cc
Ran with
%gdb a.out
GDB commands:
b main.cc:211
run
print b
(output is: 0x0)
step
step
print b
(output is: 0x4f60010)
step
step
step
step
step
print b
(output is: 0x0)
quit
This clearly indicates that your variable is getting deallocated when the function leaves its scope.
Changing the code to:
#include <malloc.h>
#include <stdio.h>
typedef struct node
{
struct node *leftChild, *rightChild;
int value;
} bst;
void insert(bst* b, int i)
{
b->value=i;
b->leftChild = NULL;
b->rightChild = NULL;
printf("[%i]",b->value);
return;
}
main()
{
bst* b;
b=(bst*)malloc(sizeof(bst));
insert(b,5);
printf("[%i]",b->value);
free(b);
}
and rerunning gdb with the following commands:
b main.cc:21
run
s
(short for step)
print b
(output: 0x1aab010)
s
s
s
s
s
s
print b
(output: 0x1aab010)
Your problem is clearly the scope of the allocation. Moving the allocation to main fixes this.
Yay your program now works!
This should give you insight into how to use the debugger to solve these kinds of simple errors in the future.
Edit:
As one op pointed out, your underlying problem is that pointers passed to functions in c are treated as local objects, so when you exit the function, any allocated memory to single pointers is tossed in the bitbucket.
Double pointers allow you to actually allocate within functions, you just have to be careful to dereference them as necessary. So your working code could also be:
#include <malloc.h>
#include <stdio.h>
typedef struct node
{
struct node *leftChild, *rightChild;
int value;
} bst;
void insert(bst** b, int i)
{
(*b)=(bst*)malloc(sizeof(bst));
(*b)->value=i;
(*b)->leftChild = NULL;
(*b)->rightChild = NULL;
printf("[%i]",(*b)->value);
return;
}
main()
{
bst* b;
insert(&b,5);
printf("[%i]",b->value);
free(b);
}