我是一个C初学者,刚刚尝试实现makeRandomTree()函数来随机创建一个二进制树。
尽管编译有时是成功的(并非总是!),但程序在运行时会以错误"Segmentation fault:11"退出。我认为错误位于makeRandomNode()-函数中,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 %in", tree->nodeValue);
printf("'NodeValue' of left child of root is %in", tree->leftChild->nodeValue);
printf("'NodeValue' of right child of root is %in", tree->rightChild->nodeValue);
printf("etc.n");
}
树处理代码总体上看起来不错,但这可能是一个问题:
printf("'NodeValue' of left child of root is %in", tree->leftChild->nodeValue);
printf("'NodeValue' of right child of root is %in", tree->rightChild->nodeValue);
如果树碰巧没有左子级或右子级,则尝试取消引用NULL
-指针。通过if (tree->leftChild) ...
进行保护