F
fabio de francesco
Hi
what do you think of the following? Why are we permitted to do that?
And why the C++ Library doesn't stop someone willing to perfom that
assignement (*a = 20)?
#include <iostream>
using std::cout;
int main()
{
int *a = new int(10);
cout << *a << " " << a << '\n';
delete a;
*a = 20;
cout << *a << " " << a << '\n';
}
After compiling (with gcc-3.4.1 on Linux and with VC++ on XP as well):
#./a.out
10 0x9f6d008
20 0x9f6d008
Maybe what is worse is that if you compile and run the above written
code without the line "*a = 20;" you get the following output:
#./a.out
10 0x9f6d008
0 0x9f6d008
I didn't know that yhis is the behaviour until I read a post on
it.comp.lang.c++ from someone who didn't understand why He got the
printed list of all the nodes of a bin-tree with a "0" output at the
position of some previously deleted nodes. So He didn't realize that
He forgot to assign NULL to the parent pointer field addressing the
just deleted nodes (and unfortunatelly all the deleted nodes were leaf
ones).
I think that if He had got a crash, dereferencing a pointer to
deallocated memory, He would had understood what was bad with his
cancelling algorithm.
So wouldn't it be better if a program crashed when someone tried to
dereference a pointer to deleted memory location?
Ciao,
Fabio De Francesco
what do you think of the following? Why are we permitted to do that?
And why the C++ Library doesn't stop someone willing to perfom that
assignement (*a = 20)?
#include <iostream>
using std::cout;
int main()
{
int *a = new int(10);
cout << *a << " " << a << '\n';
delete a;
*a = 20;
cout << *a << " " << a << '\n';
}
After compiling (with gcc-3.4.1 on Linux and with VC++ on XP as well):
#./a.out
10 0x9f6d008
20 0x9f6d008
Maybe what is worse is that if you compile and run the above written
code without the line "*a = 20;" you get the following output:
#./a.out
10 0x9f6d008
0 0x9f6d008
I didn't know that yhis is the behaviour until I read a post on
it.comp.lang.c++ from someone who didn't understand why He got the
printed list of all the nodes of a bin-tree with a "0" output at the
position of some previously deleted nodes. So He didn't realize that
He forgot to assign NULL to the parent pointer field addressing the
just deleted nodes (and unfortunatelly all the deleted nodes were leaf
ones).
I think that if He had got a crash, dereferencing a pointer to
deallocated memory, He would had understood what was bad with his
cancelling algorithm.
So wouldn't it be better if a program crashed when someone tried to
dereference a pointer to deleted memory location?
Ciao,
Fabio De Francesco