help me to find a bug....

Hello Guys,

I wrote a code to save id and password and read it using vector and structure as follows:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
  #include <iostream>
  #include <fstream>
  #include <vector>
  #include <string>

  using namespace std;

  struct user
  {
	string id;
	string pwd;
  };

  vector<user> v;

  const char* filename = "test.dat";

  int main(void)
  {
	user u;//for write
	user u1;//for read

	
	ofstream ofile;
	FILE* fp = fopen(filename, "rt");

	cout << "id: ";
	cin >> u.id;
	cout << "pwd: ";
	cin >> u.pwd;

	ofile.open(filename, ios::out|ios::binary);

	if (!ofile)
	{
		cout << "failed to open!" << endl;
		return 1;
	}
	else
		cout << "saving..." << endl;
		ofile.write((char*)&u, sizeof(user));
		cout << "save complete." << endl;
	
	ofile.close();

	while (fscanf(fp, "%s %s", &u1.id, &u1.pwd)==1)
	{
		v.push_back(u1);
	}

	fclose(fp);

	cout << v.capacity() << endl;

	for (int i = 0; i < v.capacity();i++)
		cout << v[i].id << " " << v[i].pwd << endl;
	
	system("pause");
	return 0;

      }


after building this code, I've got an error message like this:
"Exception thrown at 0x00D8B410 in Prac2.exe: 0xC0000005: Access violation writing location 0xDDDDDDDD."

It seems to have a bug in this code but I can't find it out.

If you find it out, I will appreciate it very much.

thanks for your help in advance.

seihyung
Pay attention to what your compiler tells you. When it warns you about things, you should read them.

while (fscanf(fp, "%s %s", &u1.id, &u1.pwd)==1)
This is an attempt to write into two char arrays. However, u1.id is not a char array and u1.pwd is not a char array.

This code is a horrible mish-mash of C and C++. Don't do that. Unless you've got a really good reason, just go with C++.

So no fopen. No FILE*. Use a C++ input file stream.

No fscanf. Use C++ input/output mechanisms.
At lines 53 and 55, v.capacity() should be v.size()
reference:
http://www.cplusplus.com/reference/vector/vector/capacity/
http://www.cplusplus.com/reference/vector/vector/size/

Line 41 ofile.write((char*)&u, sizeof(user)); is not valid since user contains members of type std::string. std::string will point to data held on the heap, writing such pointers to a file will not store the actual text content.

This code is a horrible mish-mash of C and C++.
It is indeed quite a mix.
Last edited on
what are you really coding? you are using 2 language at the same time :)

it looks like you got a segmentation fault, accessing a memory address that you dont own

i dont know fscanf() of C so i cant be much help here
Last edited on
Topic archived. No new replies allowed.