Reputation: 367
The idea of my project is to build a probability tree on a repeated experiment with several possible outcomes.
This is quite a simple project, and I think I did it right. It's a basic tree building : there's a building recursive function that determines node values and initializes children, and then build children.
Simplified code :
typedef struct Node {
int depth;
int noElements;
float probability;
struct Node *node0,*node1,*node4;
} Node;
void buildProbabilityTree(Node *node, int maxDepth) {
node->child1=malloc(sizeof node->child1);
//... set child1 values ...
buildProbabilityTree(node->child1,maxDepth);
node->child2=malloc(sizeof node->child2);
//... set child2 values ...
buildProbabilityTree(node->child2,maxDepth);
node->child3=malloc(sizeof node->child3);
//... set child3 values ...
buildProbabilityTree(node->child3,maxDepth);
}
int main(int argc, char *argv[]) {
Node root={0,0,1,NULL,NULL,NULL};
buildProbabilityTree(&root,3);
return EXIT_SUCCESS;
}
Full code (only 50 lines) http://pastie.org/private/cqiazmgp4bvexcidzlmutg
Problem is : it does not work!
I'm using Codeblock and GNU gcc compiler. When I run the step-to-step debug, program goes to the end with no problem. But when I build it without debugger, the program crashes when it reaches the "bottom" of the probability tree.
Anyone knows where that could come from ? A Code::Blocks option maybe ? A compiler issue ? Thanks.
Upvotes: 1
Views: 101
Reputation: 76898
(Decided to move comment to answer)
sizeof(node->node0)
doesn't do what you think it does. You just malloc'd the size of a pointer, not your struct.
Change your malloc calls to allocate sizeof(Node)
(or sizeof(*node->node0)
... though I think the former is easier on the eyes).
Upvotes: 4
Reputation: 249
I think the problem is that you only malloc(sizeof Node *). So you are only allocating memory for a pointer which is not enough!
You should malloc(sizeof Node).
Try to change malloc(sizeof node->childx) to malloc(sizeof *node->childx).
Upvotes: 1