gpt4 book ai didi

c - malloc() 调用函数 - 段错误 : 11

转载 作者:太空宇宙 更新时间:2023-11-04 06:21:09 26 4
gpt4 key购买 nike

我是 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 %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");
}

最佳答案

树处理代码一般看起来没问题,但这可能是个问题:

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);

如果这棵树碰巧没有左 child 或右 child ,您可以尝试取消引用 NULL 指针。通过 if (tree->leftChild) ...

保护它

关于c - malloc() 调用函数 - 段错误 : 11,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34765179/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com