结构指针数组分段错误

时间:2016-04-27 01:20:05

标签: c arrays pointers struct segmentation-fault

我正在构建一个自动完成程序,该程序需要输入几个字符并返回建议的字词来完成字符。我有一个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
}

1 个答案:

答案 0 :(得分:0)

好的,所以这有很多错误,你显然没有测试并编译它。但我很好奇,所以我仔细看了一下,问题源于此:

for(i = 0; w[i]; i++){ // make lowercase version of word
        w[i] = tolower(word[i]);
    }

你正潜入循环检查w[0],一个新的,未初始化的内存块。

将其更改为:

for(i = 0; word[i]; i++){ // make lowercase version of word
        w[i] = tolower(word[i]);
    }

会解决这个问题。修复上面提到的其他杂项问题,代码的非分段版本如下所示:

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

struct table {
    struct table *nextLevel[26];
    char *completions[10]; /* 10 word completions */
    int lastIndex;
}; 

int TotalMemory = 0;

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; word[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(struct table);
        *Root.nextLevel[index] = (struct table){{NULL},{NULL},0};
    }   

    struct table *pointer = Root.nextLevel[index];

    pointer->completions[0] = strdup(word); //Here is where seg fault keeps happening
}

int main(int argc, char **argv)
{
    AutoComplete_AddWord("testing");
    return 0;
}

我不能说这个程序接下来会发生什么,但至少这会让你超越段错误。