【发布时间】:2016-04-27 01:20:05
【问题描述】:
我正在构建一个自动完成程序,它需要输入几个字符并返回建议的单词来完成字符。我有一个 AutoComplete_AddWord 函数,可以添加单词以供建议。但是,每当我尝试访问我的结构完成数组(对于给定主机表的字母最多保存 10 个建议的单词)时,都会引发分段错误。不知道我哪里错了。感谢您的帮助。
struct table {
struct table *nextLevel[26];
char *completions[10]; /* 10 word completions */
int lastIndex;
};
static struct table Root = { {NULL}, {NULL}, 0 }; //global representing the root table containing all subsequent tables
void AutoComplete_AddWord(const char *word){
int i; //iterator
char *w = (char*)malloc(100*(sizeof(char));
for(i = 0; w[i]; i++){ // make lowercase version of word
w[i] = tolower(word[i]);
}
char a = 'a';
if(w[0] < 97 || w[0] > 122)
w++;
int index = w[0] - a; // assume word is all lower case
if(Root.nextLevel[index] == NULL){
Root.nextLevel[index] = (struct table*) malloc(sizeof(struct table));
TotalMemory += sizeof(table);
*Root.nextLevel[index] = (struct table){{NULL},{NULL},0};
}
else
// otherwise, table is already allocated
struct table *pointer = Root.nextLevel[index];
pointer->completions[0] = strdup(word); //Here is where seg fault keeps happening
}
【问题讨论】:
-
for(i = 0; w[i]; i++){-->for(i = 0; word[i]; i++){和w[i] = 0;在这个循环之后。 -
struct table *pointer = Root.nextLevel[index];:pointer是 else 块中的局部变量。w也有内存泄漏。 -
malloc(100*(sizeof(char)):缺少括号。sizeof(table)在 C 中应该是sizeof(struct table)。它们无法编译。 -
你应该在
nextLevel[index]之前检查index >= 0 && index < 26。
标签: c arrays pointers struct segmentation-fault