我是一名C-beginner,并且刚刚尝试实现makeRandomTree()函数来随机创建二叉树。
虽然有时编译成功(并非总是如此!),但程序在运行时会出现错误“Segmentation fault:11”。我假设错误位于makeRandomNode() - function中,其中malloc()的动态内存分配位于。不幸的是我还没有找到错误。
我希望有人可以帮助我=)
这是源代码:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define NUMBER_OF_NODES 10
#define RANDOM_NUMBER_MAX 99
struct node {
int nodeValue;
struct node *parentNode;
struct node *leftChild;
struct node *rightChild;
};
typedef struct node node;
node* makeRandomNode(unsigned int *randomSeed) {
//random number in the range [0;RANDOM_NUMBER_MAX]
int random = (rand_r(randomSeed) % (RANDOM_NUMBER_MAX + 1));
node *newNode = (node *) malloc(sizeof(node));
newNode->nodeValue = random;
newNode->parentNode = NULL;
newNode->leftChild = NULL;
newNode->rightChild = NULL;
return newNode;
}
void insertNode(node *root, node *newNode) {
if (newNode->nodeValue <= root->nodeValue) {
if (root->leftChild == NULL) {
root->leftChild = newNode;
newNode->parentNode = root;
}
else {
insertNode(root->leftChild, newNode);
}
}
else {
if (root->rightChild == NULL) {
root->rightChild = newNode;
newNode->parentNode = root;
}
else {
insertNode(root->rightChild, newNode);
}
}
}
node* makeRandomTree(int numberOfNodes) {
int i;
unsigned int randomSeed;
node *root;
node *newNode;
randomSeed = time(NULL);
root = makeRandomNode(&randomSeed);
for (i = 1; i < numberOfNodes; i++) {
newNode = makeRandomNode(&randomSeed);
insertNode(root, newNode);
}
return root;
}
int main(int argc, char *argv[]) {
node *tree = makeRandomTree(NUMBER_OF_NODES);
printf("A random-binary-tree with %i nodes was created successfully!!!\n", NUMBER_OF_NODES);
printf("'NodeValue' of root is %i\n", tree->nodeValue);
printf("'NodeValue' of left child of root is %i\n", tree->leftChild->nodeValue);
printf("'NodeValue' of right child of root is %i\n", tree->rightChild->nodeValue);
printf("etc.\n");
}
答案 0 :(得分:4)
树处理代码一般看起来不错,但这可能是一个问题:
printf("'NodeValue' of left child of root is %i\n", tree->leftChild->nodeValue);
printf("'NodeValue' of right child of root is %i\n", tree->rightChild->nodeValue);
如果树偶然没有左或右孩子,则尝试取消引用NULL
- 指针。
通过if (tree->leftChild) ...