MS Visual C++ bug?

K

Kevin Stern

Hi All,

If I type in more than 1 character in the cin portion, the delete
causes the following:

Debug Error!
Program: test.exe
DAMAGE: after Normal block (#54) at 0x002F0930.

Take a look at the following:

#include <iostream.h>

struct blah {
char a[2];
};

void main() {
blah* b;
b = new blah();
delete b;
b = new blah();
cin >> b -> a;
b -> a[1] = '\0';
delete b;

}

Any ideas?
 
J

John Harrison

Kevin Stern said:
Hi All,

If I type in more than 1 character in the cin portion, the delete
causes the following:

Debug Error!
Program: test.exe
DAMAGE: after Normal block (#54) at 0x002F0930.

Take a look at the following:

#include <iostream.h>

struct blah {
char a[2];
};

void main() {
blah* b;
b = new blah();
delete b;
b = new blah();
cin >> b -> a;
b -> a[1] = '\0';
delete b;

}

Any ideas?

Not a bug, just an array overflow. If you type two characters into cin, then
three characters will get stored in your array, the two you typed plus the
null terminator. Since your array only has room for two characters this
causes the problem.

john
 
R

Russell Hanneken

Kevin said:
If I type in more than 1 character in the cin portion, the delete
causes the following:

Debug Error!
Program: test.exe
DAMAGE: after Normal block (#54) at 0x002F0930.

Take a look at the following:

#include <iostream.h>

struct blah {
char a[2];
};

void main() {

int main() {
blah* b;
b = new blah();
delete b;
b = new blah();
cin >> b -> a;

This has the effect of calling

operator>> (cin, b->a);

b->a is an array of 2 chars, but when you pass an array as an argument
to a function, the function actually just gets a pointer to the first
element. So operator>> just gets a char *, and has no way of knowing
how large the buffer is. So when you type more than one character,
characters are written outside the bounds of the array. (The version of
operator>> that writes to a character array will always write the '\0'
at the end.) This invokes undefined behavior.

Try this:

cin.getline(b->a, 2);
b -> a[1] = '\0';

This line won't be necessary if you use getline.
delete b;

}

Any ideas?

Have you considered using std::string instead of a character array?

Regards,

Russell Hanneken
(e-mail address removed)
 
R

Russell Hanneken

Russell said:
Have you considered using std::string instead of a character array?

Or, for that matter, a char; you seem to be interested in only one
character.
 

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

No members online now.

Forum statistics

Threads
473,754
Messages
2,569,521
Members
44,995
Latest member
PinupduzSap

Latest Threads

Top