gpt4 book ai didi

c - 第二次函数调用导致段错误

转载 作者:行者123 更新时间:2023-11-30 20:08:16 25 4
gpt4 key购买 nike

我一直在尝试执行以下 C 程序。该程序执行时没有任何编译错误,但给出了“段错误”错误消息。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct Node
{
char str[100];
struct Node *children[100];
int numc;
int isd;
};

void _strsearch(struct Node *node, char *name, char *res)
{
int i = 0;
char cpy[200];
strcpy(cpy, res);
if (strcmp(node->str, "") != 0)
strcat(cpy, "/");
strcat(cpy, node->str);
for (; i < node->numc; i++)
{
_strsearch(node->children[i], name, cpy);
strcpy(cpy, res);
if (strcmp(node->str, "") != 0)
strcat(cpy, "/");
strcat(cpy, node->str);
}
if (strcmp(name, node->str) == 0)
{
strcat(res, "/");
strcat(res, node->str);
if (node->isd)
strcat(res, "/");
printf(" %s ", res);
}
}

void strsearch(struct Node *tree, char *name)
{
char path[200];
strcpy(path, tree->str);
_strsearch(tree, name, path);
}

struct Node *create_root()
{
struct Node *t = (struct Node *)malloc(sizeof(struct Node));
strcpy(t->str, "");
t->numc = 0;
t->isd = 0;
return t;
}

struct Node *add_node(struct Node *tree, char *name, int isd)
{
struct Node *t = (struct Node *)malloc(sizeof(struct Node *));
strcpy(t->str, name);
t->numc = 0;
t->isd = isd;
tree->children[tree->numc] = t;
tree->numc += 1;
return tree;
}

struct Node* del_node(struct Node *tree, char *name)
{
int i, j;
for (i = 0; i < tree->numc; i++)
{
if (strcmp(tree->children[i]->str, name) == 0)
{
for (j = i; j < tree->numc - 1; j++)
tree->children[j] = tree->children[j + 1];

tree->numc -= 1;
i -= 1;
}
}
return tree;
}

int main()
{
struct Node *tree;
struct Node *t;
tree = create_root();
tree = add_node(tree, "ay", 0);
tree = add_node(tree, "by", 0);
t = tree->children[0];
t = add_node(t, "by", 1);
t = t->children[0];
t = add_node(t, "by", 0);
t = add_node(t, "gy", 0);
strsearch(tree, "by"); // line 1
strsearch(tree, "by"); // line 2
return 0;
}

当我完全注释掉“第 2 行”时,该程序会给出所需的输出。为什么会出现这种情况?两个函数调用相同,参数相同。并且(根据我的说法)函数 _strsearch() 不会更改参数的任何值。有人可以帮助我确定此行为的实际原因吗?

注释“第 2 行”时的输出(正确):

 /ay/by/by  /ay/by/  /by

最佳答案

无论您期望什么输出,都没有什么需要纠正的。

首先初始化下面的字符缓冲区。例如

 char path[200] = {0}; /* zerod whole buffer */
char cpy[200] = {0};

其次,在add_node()函数中,内存分配应该是

struct Node *t = (struct Node *)malloc(sizeof(struct Node)); /* number of bytes should be equal to size of struct Node */

而不是

struct Node *t = (struct Node *)malloc(sizeof(struct Node *));

并检查malloc()的返回值。例如

struct Node *t = (struct Node *)malloc(sizeof(struct Node));
if(t == NULL) {
fprintf(stderr, "malloc() failed\n");
exit(1);
}

这是live demo

关于c - 第二次函数调用导致段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57542138/

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