Segmentation Fault for a Program that Indexes Words from a File

泪湿孤枕 提交于 2020-03-23 08:02:56

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!