首页 > 解决方案 > 分段错误(核心转储)需要建议

问题描述

我需要帮助为我的变量分配内存。我正在寻找导致崩溃的特定行以及如何修复它们。我在很多地方以不同的方式尝试过重新分配和 malloc。我对哪些行有问题(我的 realoc 行?)有一个粗略的想法。



int main() {
 char * myString;// myString uesd to hold users input as entered
 myString = input1(); //Get users input and stor it in myString
 int sentence_count = 0; //To keep track of the total number of lines entered
 sentence * sentences; //array of sentences to hold all the sentences as an instance of sentence
 sentences = NULL;//initialize all values
 myprint(sentence_count, sentences, myString);//Print word and lines
 search(myString, sentence_count, sentences);//Search for word in sentences
 free(myString);//free the memory set aside 

 return 0;
}


char * input1() {
   char * line;// temporary variable to one hold input line
   char * myString;//myString uesd to hold users input as entered
   line = (char * ) malloc(1024 * sizeof(char));
   myString = malloc(1024);
   myString[0] = '\0';
   line[0] = '\0';
   while (line[0] != '\n') {
       printf(" Please input a line : ");
       fgets(line, 1000, stdin);
       strcat(myString, line);//add line to mystring
   }
   free(line);
   return myString;
}

我在 PowerShell 上的 Linux 上运行它并收到以下错误

 Segmentation fault (core dumped)

标签: arrayscstringcompiler-errors

解决方案


 line = (char * ) malloc(1024 * sizeof(char));
 myString = malloc(1024);
 while (line[0] != '\n')

这里很清楚,您没有初始化line字符数组。在第一次迭代期间,line[0]未知。读取未初始化的变量是未定义的行为,可能会导致意外的程序行为。


推荐阅读