Search code examples
c++charifstreamgetlineistream

Access Violation Writing to location


Im new to c++ and I dont know what this error means. It reads from a file and tries to store the values in a char * [].

The file contains:

5,Justin,19,123-45-6789,State Farm,9876,Jessica,Broken Hand,

This is my code.

void Hospital::readRecordsFile(){
std::ifstream fileStream;
fileStream.open(fileName); // Opens the file stream to read fileName
char * temp [8];
int i = 0;
while(!fileStream.eof()){
    fileStream.get(temp[i],256,',');
    i++;
}
i = 0;
for(char * t:temp){
    std::cout << t << std::endl;
}

}

The error is at the line fileStream.get(temp[i],256,',');


Solution

  • You define an array of 8 pointers to char, but forget to allocate memory so that the pointers point to a valid chunk of memory:

    char * temp [8]; // need then to allocate memory for the pointers
    

    Because of this, in the line

    fileStream.get(temp[i],256,',')
    

    you end up using memory that's not yours.

    Solution:

    for(int i = 0; i<8; i++)
        temp[i] = new char[256]; // we allocate 256 bytes for each pointer
    

    Better though, use a std::vector<std::string> instead.


    In the code you have right now it looks like you implicitly assume that the file has no more than 8 lines, which I find hard to believe. If your file has more than 8 lines, then you'll end up accessing the array of 8 pointers out of bounds, so you'll get another undefined behaviour (usually a segfault). That's why is much better to use standard STL containers like std::vector, to avoid all these headaches.

    In case you MUST use pointers and want a variable number of lines, then you have to use a pointer to pointer,

    char** temp;
    

    then allocate memory for an enough pointers-to-char,

    temp = new char* [1000]; // we believe we won't have more than 1000 lines
    

    then, for each pointer-to-char, allocate memory

    for(int i = 0; i < 1000; ++i)
        temp[i] = new char[256];
    

    At the end of the program, you must then delete[] in reverse order

    for(int i = 0; i < 1000; ++i)
        delete[] temp[i];
    
    delete[] temp;
    

    As you can see, it's getting messy.