gpt4 book ai didi

c - malloc 的段错误

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

<分区>

我的程序中存在严重的段错误问题。

代码:

bool load(const char* dictionary)
{
// creating a trie data structure
typedef struct trie
{
bool is_word;
struct trie* alphabets[27];
}trie;
trie* root = NULL;

//opening the dictionary file
FILE* infile = fopen(dictionary, "r");
if (infile == NULL)
{
return false;
}
char s[45];
int i = 0, n = sizeof(trie);
bool start = true;
trie* tmp = NULL;
for (int c = fgetc(infile); c != EOF; c = fgetc(infile))
{
c = tolower(c);
if (isalpha(c) || c == '\'')
{
s[i] = c;
i++;
start = false;
}
else if (start == false)
{
for (int j = 0; j < strlen(s); j++)
{
int c_int = (int) (s[j] - 'a');
if (tmp == NULL || root->alphabets[c_int] == NULL)
{
root->alphabets[c_int] = malloc(n);
tmp = root->alphabets[c_int];
}
else if (tmp != NULL)
{
tmp->alphabets[c_int] = malloc(n);
tmp = tmp->alphabets[c_int];
}
else if (root->alphabets[c_int] != NULL)
{
tmp = root->alphabets[c_int];
}
if (j == strlen(s) - 1)
{
tmp->is_word = true;
}
}
}
}
return true;

root->alphabets[c_int] = malloc(n); 是出现段错误的行

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