[英]Why does my program executes in step-to-step but not in normal execution?
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 完整代码(仅50行) http://pastie.org/private/cqiazmgp4bvexcidzlmutg
Problem is : it does not work! 问题是:它不起作用!
I'm using Codeblock and GNU gcc compiler. 我正在使用Codeblock和GNU gcc编译器。 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 ? 一个Code :: Blocks选项也许? A compiler issue ? 编译器问题? Thanks. 谢谢。
(Decided to move comment to answer) (决定将评论移至答案)
sizeof(node->node0)
doesn't do what you think it does. sizeof(node->node0)
并没有您认为的那样。 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). 更改您的malloc调用以分配sizeof(Node)
(或sizeof(*node->node0)
...,尽管我认为前者更容易实现)。
I think the problem is that you only malloc(sizeof Node *). 我认为问题在于您仅使用malloc(sizeof Node *)。 So you are only allocating memory for a pointer which is not enough! 因此,您只为一个指针分配内存是不够的!
You should malloc(sizeof Node). 您应该malloc(sizeof Node)。
Try to change malloc(sizeof node->childx) to malloc(sizeof *node->childx). 尝试将malloc(sizeof node-> childx)更改为malloc(sizeof * node-> childx)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.