file.read( (TCHAR*)&name_length, sizeof(unsigned int) );

R

r.z.

This piece of code crashes my app:
basic_ifstream<TCHAR> file(levelfilepath, ios_base::binary);
unsigned int name_length;
file.read( (TCHAR*)&name_length, sizeof(unsigned int) ); //crashes here -
file is open and contains binary data

It may take me hours to find out why this is incorrect, so if you know it,
please tell me.
 
R

r.z.

Why? This is runtime error and I indicated the exact place where my app
crashes. Nothing more is necessary to tell whether this code is safe or not.
 
M

Michael

r.z. said:
This piece of code crashes my app:
basic_ifstream<TCHAR> file(levelfilepath, ios_base::binary);
unsigned int name_length;
file.read( (TCHAR*)&name_length, sizeof(unsigned int) ); //crashes here -
file is open and contains binary data

It may take me hours to find out why this is incorrect, so if you know it,
please tell me.

Add the following code. It should help you debug the problem:

#include <assert.h>

assert(sizeof(unsigned int) == 4);
assert(sizeof(TCHAR) == 2);
unsigned int num_bytes_read = sizeof(unsigned int) * sizeof(TCHAR);
assert(num_bytes_read == 8);

unsigned int space_available_for_reading_into = sizeof(name_length);
assert(space_available_for_reading_into == 4);

assert(4 < 8);

If you're really reading a binary file, you probably shouldn't be using
TCHAR. In other words, if I recompile your code with Unicode
enabled/disabled, your code will have different behavior.

Michael
 
D

David Harmon

On Thu, 28 Dec 2006 21:23:47 +0100 in comp.lang.c++, "r.z."
of course TCHAR == wchar_t

Well, there is your problem. Change TCHAR to (unsigned char).
You are reading (sizeof TCHAR)*(sizeof int) bytes into a variable
that is only (sizeof int).

By the way, "TCHAR" is probably a bad choice of a name, since you will
find Microsoft using it all over much of their code. Even though you
may have nothing to do with Windows systems, you are likely to run into
a conflict sooner or later -- this problem may be it! Just as you would
never start a class name with "C" as they have de-facto reserved that
letter for Microsoft classes.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,482
Members
44,900
Latest member
Nell636132

Latest Threads

Top