问题
I am getting a segmentation fault for a C program that first reads the characters of a given file, identifies words, indexes words, and prints the first word. I have been troubleshooting for a long time but cannot seem to find what the error is.
#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;
}
回答1:
Just like @Zen said, a SEGFAULT
will occur if you try to access a memory location you are not allowed to or not allocated.
Your program terminates just after the first iteration because i
becomes 1
at that moment and text[1]
becomes inaccessible because text
was allocated the size of a single character only:
char *text = malloc(sizeof(char));
here.
Yet, I have not checked your algorithm right now so I am only providing an initial observation. If any errors still pop up, feel free to post on this thread here.
Best.
来源:https://stackoverflow.com/questions/60312688/segmentation-fault-for-a-program-that-indexes-words-from-a-file