索引文件中单词的程序的分段错误 [英] Segmentation Fault for a Program that Indexes Words from a File

查看:49
本文介绍了索引文件中单词的程序的分段错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一个C程序的分段错误,该程序首先读取给定文件的字符,识别单词,索引单词并打印第一个单词。我已经进行了很长一段时间的故障排除,但似乎找不到错误所在。

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;
}


推荐答案

就像@Zen所说,如果尝试访问不允许或未分配的内存位置,则会发生 SEGFAULT

Just like @Zen said, a SEGFAULT will occur if you try to access a memory location you are not allowed to or not allocated.

您的程序在第一次迭代后终止,因为此时 i 变为 1 text [1 ] 变得不可访问,因为 text 仅分配了单个字符的大小:
char * text = malloc (sizeof(char)); 在这里。

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.

最好。

这篇关于索引文件中单词的程序的分段错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆