I am getting access violation error when I run the following code on Visual studio. Perhaps I am trying to read some pointer location that I have not allocated or something, But I cannot seem to find where the problem exactly is. Need some help with the same.
#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;
}
There is no protection on
jexceeding number of elements inlines:If file contains more that
56000lines, then this will access beyond the bounds of the array.As this is C++, you should consider using
ifstream,std::getline()andstd::vector<std::string>to read the file.std::vector<std::string>will manage the memory allocation for you: