繁体   English   中英

为什么这个 C 代码(读取文件)在退出(或文件重新分配)时崩溃?

[英]Why does this C code (reading a file) crash upon exit (or file reallocation)?

以下代码在程序退出之前崩溃。 我已经在 MSVS 2015 和 GCC 上对其进行了测试。该程序只是在堆上分配一个 VLA(如果需要,请在此处阅读)并逐个字符地读取文件内容并将该字符存储在数组中。 该程序运行良好。 它可以正确打印所有内容。 但是,退出后它会崩溃,或者它会停止响应。

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>

#define rows 8
#define columns 8

// allocate a VLA on the heap
void allocateVLArray(int x, int y, char(**ptr)[rows][columns])
{
    *ptr = malloc(sizeof(char[rows][columns]));
    assert(*ptr != NULL);
}

int main()
{
    char (*grid)[rows][columns];
    allocateVLArray(rows, columns, &grid);

    if (grid) {
        FILE *inputFile = fopen("test_fgetc.txt", "r");
        if (inputFile) {
            int x = 0, y = 0, length = 0;
            char ch;

            while((ch = (char)fgetc(inputFile)) != EOF) {
                // CR and LF characters are captured together (if necessary) and counted as one char using '\n'
                if (ch == '\n') {
                    x++; y = 0;
                }
                else {
                    *grid[x][y] = ch;
                    y++;
                }
                length++;
            }

            for (x = 0; x < rows; x++) {
                for (y = 0; y < columns; y++) {
                    printf("%c", *grid[x][y]);
                }
                printf("\n");
            }

            printf("\nlength = %d\n", length);
        }
    }

    free(grid);

    return 0;
}

我还注意到我的常量 memory 使用量显着增加,这意味着 memory 泄漏。 所以这可能是一个堆问题。 为什么会发生这种情况,我该如何解决?

可能发生的情况是您的"test_fgetc.txt"包含超过 64 个字符,或超过 8 行字符。 这将准确地展示您正在经历的行为:它似乎可以工作,并且会在free()上崩溃。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM