c++ - 在 Visual C++ 中接收关于 fgets() 的访问冲突错误

标签 c++ visual-c++ file-io

当我在 Visual Studio 上运行以下代码时出现访问冲突错误。也许我正在尝试读取一些我没有分配的指针位置或其他东西,但我似乎无法找到问题的确切位置。需要一些帮助。

#include <iostream>

class fileReader
{
public:
    FILE *fp;
    char** lines;
    fileReader()
    {
        fp = NULL;
    }
    fileReader(char* path)
    {
        int j=0;
        fp = fopen(path,"r");
        if (fp == NULL) 
            return;
        else 
        {
            lines = (char**) malloc(sizeof(char *)*56000);
            for (int i=0; i<56000; i++)
                lines[i] = (char*)malloc(sizeof(char)*1440);
            while ( fgets(lines[j], 1440, fp) )
                j++;
            fclose(fp);
        }
    }
};

int main(int argv, char** argc)
{
    char* path = "D:\\testfile.txt";
    fileReader *p = new fileReader(path);
    for (int i=0; i<2; i++)
        std::cout<<p->lines[i];
    return 0;
}

最佳答案

j 没有保护lines 中的元素数量超过:

while ( fgets(lines[j], 1440, fp) )
    j++; 

如果文件包含更多 56000行,那么这将超出数组的范围。

因为这是 C++,你应该考虑使用 ifstream , std::getline()std::vector<std::string>读取文件。 std::vector<std::string>将为您管理内存分配:

std::vector<std::string> lines;
std::ifstream in("D:\\testfile.txt");

if (in.is_open())
{
    std::string line;
    while (std::getline(in, line))
    {
        lines.push_back(line);
    }
    in.close();
}

关于c++ - 在 Visual C++ 中接收关于 fgets() 的访问冲突错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9767547/

相关文章:

c++ - 如何让 C++ 编译器间接推导 T?

c++ - 负 ASCII 值

c++ - realloc 指针在功能失效时发生变化

C++ 插入对象列表

file-io - 空中位置存储文件的区别

多种颜色的 C++ DirectX DrawText

c++ - 如何在派生类中可移植地初始化继承的模板化 POD 结构?

c++ - stdafx 是否需要在同一目录中?

file-io - 如何倒序写入文件

matlab - 如果 csvread 失败则跳过文件 Matlab