我正在尝试编写将二进制树转换为链接列表的C程序。以下是这些结构的声明:
struct treeNode {
double data;
struct treeNode* leftP;
struct treeNode* rightP;
};
struct listNode{
double data;
struct listNode* nextP;
};
该算法有效,但我希望在程序执行结束时出现内存错误(进程返回0xC0000005)。在使用此代码进行一些搜索之后,我猜它来自指针的错误管理,但我找不到我的错误。这是我的主要功能:
int main()
{
/*Creation of the binary tree*/
struct treeNode tree[10];
int i;
for(i=0;i<10;i++)
tree[i].data = (float)i;
tree[0].leftP = &(tree[1]);
tree[0].rightP = &(tree[2]);
//....... (creation of the tree)
tree[9].rightP = 0;
//Conversion
void** elem = malloc(sizeof(void**));
*elem = (void*)(&tree);
tree2list(elem);
struct listNode* list = (struct listNode*)(*elem);
printList(list);
printf("end1");
//free(elem);
printf("end2\n");
return 0;
}
如果我评论自由线,则程序到达end2,如果我尝试释放变量elem,则结束end1。这是tree2list函数:
void tree2list(void** node)
{
struct treeNode* tree = (struct treeNode*)(*node); //tree to convert
int size = treeSize(tree);
struct listNode* list = malloc(size*sizeof(struct listNode*)); //Creation of a list with same number of nodes than in the tree
*node = (void*) list;
struct listNode* currentListNode = list;
struct treeNode* currentTreeNode = tree;
struct treeNode* nextNode;
struct listNode* old = 0;
struct treeNode* stack = 0; //Stack composed of treeNode linked by their leftP pointer
while(currentTreeNode)
{
if(currentTreeNode->leftP) //if left branch exists, add the current node to the stack and explore this left branch
{
nextNode = currentTreeNode->leftP;
stackPush(&stack, currentTreeNode);
currentTreeNode = nextNode;
}
else //if left branch doesn't exist, add the currentNode to the list
{
currentListNode->data = currentTreeNode->data;
currentListNode->nextP = 0;
if(old)
old->nextP = currentListNode;
old = currentListNode++;
if(currentTreeNode->rightP)
currentTreeNode = currentTreeNode->rightP;
else
currentTreeNode = stackPop(&stack);
}
}
}
其他函数的功能,如stackPush和stackPop似乎运行良好。有人看到错误代码的来源吗?
由于
答案 0 :(得分:1)
void** elem = malloc(sizeof(void**));
这没有任何意义。想想你在这里尝试做什么。同样,这也没有任何意义:
struct listNode* list = malloc(size*sizeof(struct listNode*));
在第一个malloc中,你可能应该分配一个指针数组,然后用指针指向它们。您分配了一个指向指针的指针。如果这是意图,为什么要首先动态分配它?
在第二个malloc中,你可能应该分配一个结构数组。你分配了一个指向结构的指针数组。
而不是分配在整个堆中分段的指针到指针查找表,考虑properly allocating a 2D array。