簡體   English   中英

C char ** 讀取或 fclose 上的 Seg 錯誤

[英]C Seg fault on char ** reading or fclose

在我的代碼中,我試圖讀取一個文件,讀取它的行並將它們放入一個字符串數組中,然后打印它們並關閉文件。 當我運行它時,它因段錯誤而失敗並跳過文件的最后一行,我就是找不到問題......我的直覺是責怪錯誤地讀取數組或文件行為不端......我是我對嗎? 任何幫助或重定向都會有所幫助。 謝謝!

這是主文件:

#include "files_utils.h"

int main()
{
    FILE *fp = fopen("expl", "r");
    if (!fp)
        return -1;
    long lines_count = countlines(fp);
    long flen = file_length(fp);
    String *lines = calloc(lines_count, sizeof(String));
    printf("file length: %ld\n", flen);
    printf("file lines: %ld\n", lines_count);
    getlines(lines, lines_count, fp);
    printf("finished\n");
    for (String *sp = lines; sp != NULL; sp++)
        printf("%s", *sp);
    printf("before close\n");
    fclose(fp);
    printf("closed\n");
    return 0;
}

這是 files_utils 文件:

#include <stdio.h>
#include <stdlib.h>
#define MAXLINE 10

typedef char *String;

long file_length(FILE *fp)
{
    /*
    find the length of the file fp points to, regardless of the current position.
    */
    long original_pos = ftell(fp), i = 0;
    rewind(fp);
    // count chars:
    for (int c = fgetc(fp); c != EOF; c = fgetc(fp))
        i++;
    // return the file to it's original position
    fseek(fp, original_pos, SEEK_SET);
    return i;
}

long countlines(FILE *fp)
{
    /*
    find the amount of lines in file fp points to, regardless of the current position.
    */
    long original_pos = ftell(fp), i = 0;
    rewind(fp);
    // find newlines:
    for (int c = fgetc(fp); c != EOF; c = fgetc(fp))
        if (c == '\n')
            i++;
    // return the file to it's original position
    fseek(fp, original_pos, SEEK_SET);
    return i;
}

String *getlines(String lines[], long maxlines, FILE *fp)
{
    for (int i = 0; i <= maxlines; i++)
    {
        lines[i] = calloc(MAXLINE, sizeof(char));
        fgets(lines[i], MAXLINE, fp);
    }
    return lines;
}

它輸出

file length: 144
file lines: 21
finished
... all the lines of the file except of the last one ...
Segmentation fault (core dumped)

當我將打印循環更改為運行到 maxlines 而不是等待 NULL 時,問題得到了解決。 為什么是這樣? 為什么等待 NULL 會引發段錯誤?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM