C代码报Segmentation fault? 400 报错
自己照着数据结构写了个二叉树的先序遍历:
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct TreeNode *BinTree; typedef BinTree position; struct TreeNode{ const char *data; BinTree left; BinTree right; }; /** * 先序遍历二叉树 */ void preOrderTraversal(BinTree tree); BinTree createChildTree(BinTree tree, char const *left_data, char const *right_data); BinTree initTree(); const char *alphbet = "ABCDFGIEH"; int main(int argc, char const *argv[]) { // create binary tree... BinTree tree = initTree(); preOrderTraversal(tree); return 0; } void preOrderTraversal(BinTree tree){ // more smarter way... if(tree){ printf("node data of tree is %s\n", tree->data); preOrderTraversal(tree->left); preOrderTraversal(tree->right); } } BinTree initTree(){ // root tree node.... BinTree tree = (BinTree) malloc(sizeof(TreeNode)); tree->data = &alphbet[0]; tree->left = NULL; tree->right = NULL; // second level... createChildTree(tree, &alphbet[1], &alphbet[2]); // third level... createChildTree(tree->left, &alphbet[3], &alphbet[4]); createChildTree(tree->right, &alphbet[5], &alphbet[6]); // fourth level,not complete createChildTree(tree->left->right, &alphbet[7], NULL); createChildTree(tree->right->left, NULL, &alphbet[8]); return tree; } BinTree createChildTree(BinTree tree, const char *left_data, char const *right_data){ if(left_data){ BinTree left = (BinTree) malloc(sizeof(BinTree)); left->data = left_data; left->left = NULL; left->right=NULL; tree->left = left; } if(right_data){ BinTree right = (BinTree) malloc(sizeof(BinTree)); right->data = right_data; right->left = NULL; right->right = NULL; tree->right = right; } return tree; }
运行的时候的异常信息如下:
clang: warning: treating 'c' input as 'c++' when in C++ mode, this behavior is deprecated
bash: line 1: 2401 Segmentation fault: 11 '/Users/apple/dev/study/data_struct/temp'
[Finished in 0.1s with exit code 139]
我的环境是mac + sublime text。
请问下,我代码哪里出错了????
段错误一般是访问无效内存导致吧
###### The function of createChildTree return a value, but the function of initTree dosen't take over the value, so the code occurs Segmentation fault.######接收返回值也是一样的。。 it doesn't work######这段编译应该都过不了
BinTree tree = (BinTree) malloc(sizeof
(TreeNode));
segmentation falut多数是由于类型不匹配 楼上说的结构体那里的确有问题
改成sizeof(struct TreeNode)或者
BinTree tree; sizeof(*tree)
######谢谢哈,原因确实是这样######sizeof(BinTree)有问题,BinTree是一个指针,而不是结构体######谢谢哈,已经解决啦版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。