从文件中索引单词的程序的分段错误
Segmentation Fault for a Program that Indexes Words from a File
我遇到了 C 程序的分段错误,该程序首先读取给定文件的字符、识别单词、索引单词并打印第一个单词。我已经进行了很长时间的故障排除,但似乎无法找到错误所在。
#include <stdio.h>
#include <stdlib.h>
#include <cs50.h>
#include <string.h>
int main (int argc, char *argv[])
{
if (argc != 2)
{
printf("Usage: ./test15 text\n");
return 1;
}
char *file = argv[1];
FILE *ptr = fopen(file, "r");
char ch;
int i = 0;
int k = 0;
int j = 0;
char *text = malloc(sizeof(char));
string word[k];
while ((ch = fgetc(ptr)) != EOF)
{
text[i] = ch;
if (ch == ' ')
{
for (int l = j; l < i; l++)
{
strcat(word[k], &text[l]);
}
k++;
j = i;
}
i++;
}
printf("%s\n", word[0]);
return 0;
}
正如@Zen 所说,如果您尝试访问不允许或未分配的内存位置,则会发生 SEGFAULT
。
您的程序在第一次迭代后立即终止,因为 i
在那一刻变为 1
并且 text[1]
变得不可访问,因为 text
被分配了单个字符的大小只要:
char *text = malloc(sizeof(char));
这里。
但是,我现在还没有检查你的算法,所以我只是提供一个初步的观察。如果仍然弹出任何错误,请随时在此线程上 post。
最佳。
我遇到了 C 程序的分段错误,该程序首先读取给定文件的字符、识别单词、索引单词并打印第一个单词。我已经进行了很长时间的故障排除,但似乎无法找到错误所在。
#include <stdio.h>
#include <stdlib.h>
#include <cs50.h>
#include <string.h>
int main (int argc, char *argv[])
{
if (argc != 2)
{
printf("Usage: ./test15 text\n");
return 1;
}
char *file = argv[1];
FILE *ptr = fopen(file, "r");
char ch;
int i = 0;
int k = 0;
int j = 0;
char *text = malloc(sizeof(char));
string word[k];
while ((ch = fgetc(ptr)) != EOF)
{
text[i] = ch;
if (ch == ' ')
{
for (int l = j; l < i; l++)
{
strcat(word[k], &text[l]);
}
k++;
j = i;
}
i++;
}
printf("%s\n", word[0]);
return 0;
}
正如@Zen 所说,如果您尝试访问不允许或未分配的内存位置,则会发生 SEGFAULT
。
您的程序在第一次迭代后立即终止,因为 i
在那一刻变为 1
并且 text[1]
变得不可访问,因为 text
被分配了单个字符的大小只要:
char *text = malloc(sizeof(char));
这里。
但是,我现在还没有检查你的算法,所以我只是提供一个初步的观察。如果仍然弹出任何错误,请随时在此线程上 post。
最佳。