当我在 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/