[英]Issue with Segmentation Faults using Double Pointers in C
因此,我的目标是创建一系列特定的单词。 这是我正在使用的当前代码:
char **specificWords; //Global
specificWords = malloc(100 * sizeof( char *));
int addToArray(char * word, int i){
specificWords[i] = word;
printf("%s\n", specificWords[i]);
return 0;
}
现在只是假装在函数中,函数是使用递增的“ i”值和新的“ words”反复调用函数。 函数内部的print语句工作正常,但是,如果我尝试在函数外部使用相同的print语句,则程序会因seg错误错误而关闭。
我对C编程还是很陌生,但是我尝试了许多不同的事情,从每次调用数组时为数组分配空间就可以了。 对于不同的递增方法,例如“(** specificWords)++”,仅在主体中使用循环,但我真的无法弄清楚。
让我知道是否需要澄清,谢谢。
编辑:这是主要...我正试图发布一个程序来解释我的问题,所以这是真正的一个:
char **specificWords; //Global
char *globalString;
int main(int argc, char* argv[]) {
specificWords = malloc(100 * sizeof( char *));
int newLineCount = countLines(globalString);
addToArray(newLineCount);
printf("%s\n", specificWords[0]); //segFaults
return 0;
}
int addToArray(int newLineCount){
int ch;
int loc = 0;
char *tempKeyword;
char temp[5026];
int j = 0;
int k = 1;
j = 0;
for(int i = 0; i < newLineCount; i++){
while(1){
//I read in a file and made the whole thing one big string which is global string
ch = globalString[loc];
if(ch == '\n')
break;
temp[j] = ch;
loc++;
j++;
}
loc++;
temp[j] = '\0';
tempKeyword = temp;
specificWords[k] = tempKeyword;
printf("%s\n", specificWords[k]);
//k++; // if used seg faults...
}
}
您存储的指针word
可能超出范围或以其他某种方式变为无效。
直接像您一样直接存储指针是错误的,也许addToArray()
函数应该存储strdup(word)
的返回值。 当然,您还需要测试它是否失败,因为它分配了内存。
您已经使用了本地字符串变量char temp[5026];
定义在函数内部,该函数在退出函数后将不复存在,因此您的printf可以完美地在函数中工作,但是如果您尝试在addToArray
之外进行打印,则会崩溃。
说明:
{ // this is a block of code, for example function body char word[128]; // this string will exist at this level of code // it will work perfectly at this level } // now, there's no word variable at all, any pointer to it's address (data) // is invalid and could crash or you would read garbage from it
在这一行:
tempKeyword = temp; specificWords[k] = tempKeyword;
您总是为每个单词分配整个临时缓冲区,因此您将始终在所有specificWords索引中获得第一个单词,例如,在specificWords[2]
。 要遵循unwind的建议,请从头开始重写代码以将每个单词都读取到temp,然后使用strdup将单词复制到动态分配的内存中,以从函数返回后继续存在。 在您的for循环中:
j = 0; // always reset the position to buffer from beginning while(1){ //I read in a file and made the whole thing one big string which is global string ch = globalString[loc]; if(ch == '\\n') break; temp[j] = ch; loc++; j++; } loc++; temp[j] = '\\0'; tempKeyword = strdup(temp); specificWords[k] = tempKeyword; printf("%s\\n", specificWords[k]);
您正在从这一行的1开始计算单词索引:
int k = 1;
在C语言中,数组中的索引从零开始,因此您由于specificWords
容量损失了一个单词,因此您最多可以在数组中存储99个单词。 为了解决这个问题,您可以从索引k=0
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.