<badptr> Error when Reading From Binary File

Hello everyone,

In my application, I keep students' records in a struct as

1
2
3
4
5
struct Record
{
	Student pupil;
	int index;
};


And Student class as

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Student
{
public:
	Student()
	{
		number = 0;
		name = new char[30];
		mid1 = 0;
		mid2 = 0;
		lab = 0.0;
		final = 0;
	}

	int number;
	char* name;
	int mid1;
	int mid2;
	double lab;
	int final;
};

Until, I exit the program, it does not give any error and run truthfully. I can write or read any records. However, when I exit and run it again and read records, names is read as <BadPtr>. But other fields in the structure be correct.

Can anyone tell me, where is my mistake?
You have a memory leak. Whenever you use the new keyword you need a delete keyword to counter it. Otherwise your program will explode.

Add this destructor to your class to avoid this problem (or delete the data some other way).
1
2
3
4
~Student()
{
  delete name;
}
Last edited on
Wouldn't it be:

delete[] name;
When you are pulling data from the file are you perhaps pulling more than 29 characters for name? Remember to allocated space for the full amount of characters + the null terminator.
After adding destructor, it got worse. Now, it cannot write names to the file, just write some strange characters and <badptr> error continues...


Texan40:

Do I allocate more than 30 bit for name?
Can you show how you are reading and writing to file?
For example in insert() function:

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
        Record rec;
	char newLine;

	cout<<"Enter student number: ";
	.
	.
	.
	cout<<"Enter student name: ";
	cin.getline( &newLine, 1 );
	cin.getline(rec.pupil.name, 30);
	.
	.
	.

	int address = rec.pupil.number % MOD;

	Record check;
	fstream com252("com252list.dat", ios::binary | ios::in | ios::out );
	com252.seekg( address*sizeof( Record ), ios::beg );
	com252.read( reinterpret_cast<char *>( &check ), sizeof( Record ) );


	if( check.pupil.number == 0 )
	{
		com252.seekp( address*sizeof( Record ), ios::beg );
		com252.write( reinterpret_cast<char *>( &rec ), sizeof( Record ) );
		com252.close();
	}
	.
	.
	.


After "com252.read( reinterpret_cast<char *>( &check ), sizeof( Record ) );" line, check.pupil.name be <badPtr>
Last edited on
Are you sure the file com252list.dat exist? I think you have to pass ios::app or ios::trunc to fstream if you want it to create the file if it doesn't exist.

name is just a pointer so you are only storing the pointer in the file, and not the actual data. You need to handle the reading and writing of name separately.
Yeah, when program starts, it creates file if not exist.

If I use string rather than char *, problem is solved?
Last edited on
No.
Should be. The string template has it's own overloaded operator>> and operator<<
Topic archived. No new replies allowed.