Access Violation Reading File


I'm getting this acess error trying to read in from a file.

Error
1
2
3
First-chance exception at 0x77cf8dc9 in Testing_OpenGL.exe: 0xC0000005: Access violation writing location 0x00000014.
Unhandled exception at 0x77cf8dc9 in Testing_OpenGL.exe: 0xC0000005: Access violation writing location 0x00000014.
The program '[8460] Testing_OpenGL.exe: Native' has exited with code -1073741819 (0xc0000005).



Here is the code. It breaks on line 16
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
std::vector<std::string*> coord;


	//Open the file
	std::ifstream in(filename);
	if( !in.is_open())
	{
		fprintf(stderr, "Object not opened!");
		return -1;
	}

	//Read the file
	char buf[256];
	while(!in.eof())
	{
		in.getline(buf,256);
		coord.push_back(new std::string(buf));
	}
Two issues:
1) You're not checking if the getline fails, thereby attempting to push a garbage string.
2) If the getline fails, you have no guarantee that buf is terminated with a null, therefore the new string can continue searching past buf[255] for a null terminator resulting in an access violation.
Im not sure how to fix any of those problems :(. Could you tell me or point me in the right direction? I tried google but i can't find anything.
Check the state of in after performing the getline() to see if it was successful.
Why are you using manually managed dynamic memory here?

1
2
3
4
5
6
7
8
9
10
11
12
13
    std::vector<std::string> coord;

    //Open the file
    std::ifstream in(filename);
    if( !in.is_open())
    {
        fprintf(stderr, "Object not opened!");
        return -1;
    }

    std::string buf ;
    while ( std::getline(in, buf) )
        coord.push_back(buf) ;


Last edited on
I changed my code a bit, but im still getting the same error, this time on line 19.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
	//Open the file
	std::ifstream in(filename);

	if( in.fail())
	{
		fprintf(stderr, "Object not opened!");
		return -1;
	}

	//Read the file
	if( !in.is_open() )
	{
		fprintf(stderr, "Object not opened!");
        return -1;
	}
	else
	{
		std::string buf;
		while(std::getline(in, buf) )
			coord.push_back(buf);
	}
Last edited on
I replicated this segment of code in a diferent project and it worked. It's the exact same code in the non-working-project, too.
Last edited on
Topic archived. No new replies allowed.