arrays - 分段错误(核心转储)需要建议
问题描述
我需要帮助为我的变量分配内存。我正在寻找导致崩溃的特定行以及如何修复它们。我在很多地方以不同的方式尝试过重新分配和 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)
解决方案
line = (char * ) malloc(1024 * sizeof(char));
myString = malloc(1024);
while (line[0] != '\n')
这里很清楚,您没有初始化line
字符数组。在第一次迭代期间,line[0]
未知。读取未初始化的变量是未定义的行为,可能会导致意外的程序行为。
推荐阅读
- java - 用于记录的动态实体拾取
- javascript - IE 中容器的奇怪行为
- sql-server - 如何在sql server ro14中查找死锁原因?
- react-native - 将项目转换为反应本机初始化
- jquery - 我真的需要使用 touchstart 还是只需单击即可完成工作?
- magento - magento 为产品和页面图像上传动画 gif 不起作用
- android - 如何更新opencv管理器?
- mongodb - 如何使用 Golang 从 MongoDB 中的特定键中获取值
- java - 奥利奥:java.lang.IllegalStateException
- c# - 将字符串转换为 TimeSpan 类型