473,327 Members | 2,016 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,327 software developers and data experts.

This code must have crashed....but works fine

Consider the below code snippet:

#include <iostream>
using namespace::std;

class myclass
{
public:
myclass() {
cout << "constructor" << endl;
}
~myclass() {
cout << "destructor" << endl;
}
void func() {
cout << "func" << endl;
}
};

int main(void) {
myclass *obj = new myclass();
delete obj;
obj = NULL; // obj = (myclass*)0;
obj->func(); //..............must be a crash..... but works fine
return 0;
}

i tried the above code in Microsoft compiler 12.0, 13.0 and g++.
the code doesnt crash and the output will be like
constructor
destructor
func

i really dont know how when obj is null, obj->func() is valid and not
crashing ?????????????/

anybody has an idea about it ??????????

regards,
Harsha.

Aug 18 '06 #1
14 1560
hs******@gmail.com schrieb:
Consider the below code snippet:
[snip]
int main(void) {
myclass *obj = new myclass();
delete obj;
obj = NULL; // obj = (myclass*)0;
obj->func(); //..............must be a crash..... but works fine
return 0;
}

i tried the above code in Microsoft compiler 12.0, 13.0 and g++.
Where did you get that compiler? MS C++ is at version 8.0.
the code doesnt crash and the output will be like
constructor
destructor
func

i really dont know how when obj is null, obj->func() is valid and not
crashing ?????????????/
Your code invokes undefined behaviour by dereferencing a null-pointer.
Undefined means, the compiler is free to do everything it wants: It might
appear to work this time, or it might format your hard disk.

--
Thomas
Aug 18 '06 #2

hshar...@gmail.com wrote:
Consider the below code snippet:

#include <iostream>
using namespace::std;

class myclass
{
public:
myclass() {
cout << "constructor" << endl;
}
~myclass() {
cout << "destructor" << endl;
}
void func() {
cout << "func" << endl;
}
};

int main(void) {
myclass *obj = new myclass();
delete obj;
obj = NULL; // obj = (myclass*)0;
obj->func(); //..............must be a crash..... but works fine
Actually, that merely results in undefined behavior.
return 0;
}

i tried the above code in Microsoft compiler 12.0, 13.0 and g++.
the code doesnt crash and the output will be like
constructor
destructor
func

i really dont know how when obj is null, obj->func() is valid and not
crashing ?????????????/

anybody has an idea about it ??????????
When you have undefined behavior, that means anything could happen.
For example (1) the program might crash, (2) the program might work as
if you had a valid object (since your class has no members and
therefore the null pointer is never dereferenced), or (3) the program
might print "Harsha uses far too many question marks ('?') in his
postings" on your console over and over again. If it's undefined, you
just don't know.

Best regards,

Tom

Aug 18 '06 #3
hs******@gmail.com wrote:
Consider the below code snippet:

#include <iostream>
using namespace::std;

class myclass
{
public:
myclass() {
cout << "constructor" << endl;
}
~myclass() {
cout << "destructor" << endl;
}
void func() {
cout << "func" << endl;
}
};

int main(void) {
myclass *obj = new myclass();
delete obj;
obj = NULL; // obj = (myclass*)0;
obj->func(); //..............must be a crash..... but works fine
The C++ standard doesn't require any code to 'crash'.
return 0;
}

i tried the above code in Microsoft compiler 12.0, 13.0 and g++.
the code doesnt crash and the output will be like
constructor
destructor
func

i really dont know how when obj is null, obj->func() is valid and not
crashing ?????????????/
What makes you think there is no other possible outcome than a 'crash'?
anybody has an idea about it ??????????
Try to repair your '?' key. It seems broken.
Aug 18 '06 #4
<hs******@gmail.comwrote in message
news:11**********************@i42g2000cwa.googlegr oups.com...
i really dont know how when obj is null, obj->func() is valid and not
crashing ?????????????/

anybody has an idea about it ??????????
Unfortunately, C++ doesn't have strict rules about what happens when you do
something naughty like this. When you call obj->func(); with obj==NULL, the
behaviour is undefined. That means that it may, fortuitously, work exactly
as expected; but this is no guarantee that it works on any other compiler.

You may get different results if you add a variable to myclass and access it
from func(); you may not. Either way, you are correct, this code is wrong,
but the compiler may not be able to warn you about it.

Philip

Aug 18 '06 #5

Philip Potter wrote:
<hs******@gmail.comwrote in message
news:11**********************@i42g2000cwa.googlegr oups.com...
i really dont know how when obj is null, obj->func() is valid and not
crashing ?????????????/

anybody has an idea about it ??????????

Unfortunately, C++ doesn't have strict rules about what happens when you do
something naughty like this. When you call obj->func(); with obj==NULL, the
behaviour is undefined. That means that it may, fortuitously, work exactly
as expected; but this is no guarantee that it works on any other compiler.

You may get different results if you add a variable to myclass and access it
from func(); you may not. Either way, you are correct, this code is wrong,
but the compiler may not be able to warn you about it.

Philip
i tried it in microsoft cl 6.0, 7.0 and g++ (suprisingly same
behaviour). all the three give the same result. if its undefined, then
there must be some variations in the output, but its the same. i am
really confused.
i even tried adding a variable to the class, but the result was the
same. u guys can try it on any compiler and let me know if possible. i
doubt something in this.

Aug 18 '06 #6

<hs******@gmail.comwrote in message
news:11*********************@m73g2000cwd.googlegro ups.com...
>
Philip Potter wrote:
><hs******@gmail.comwrote in message
news:11**********************@i42g2000cwa.googleg roups.com...
i really dont know how when obj is null, obj->func() is valid and not
crashing ?????????????/

anybody has an idea about it ??????????

Unfortunately, C++ doesn't have strict rules about what happens when you
do
something naughty like this. When you call obj->func(); with obj==NULL,
the
behaviour is undefined. That means that it may, fortuitously, work
exactly
as expected; but this is no guarantee that it works on any other
compiler.

You may get different results if you add a variable to myclass and access
it
from func(); you may not. Either way, you are correct, this code is
wrong,
but the compiler may not be able to warn you about it.

Philip

i tried it in microsoft cl 6.0, 7.0 and g++ (suprisingly same
behaviour). all the three give the same result. if its undefined, then
there must be some variations in the output, but its the same. i am
really confused.
i even tried adding a variable to the class, but the result was the
same. u guys can try it on any compiler and let me know if possible. i
doubt something in this.
The term "undefined" means that the Standard for C++ does not define what
the results should be. It is simply up to to you to avoid undefined
behavior at all times. It makes no difference if it happens to do the exact
same thing on every compiler and every computer in existence. It's improper
to do that, and the results are not specified by the Standard. You should
not rely on it working, or crashing, or on any specific behavior at all.
Just don't do that! :-)

-Howard

Aug 18 '06 #7
hs******@gmail.com wrote:
><hs******@gmail.comwrote in message
news:11**********************@i42g2000cwa.googleg roups.com...
i really dont know how when obj is null, obj->func() is valid and not
crashing ?????????????/

anybody has an idea about it ??????????

Unfortunately, C++ doesn't have strict rules about what happens when you
do something naughty like this. When you call obj->func(); with
obj==NULL, the behaviour is undefined. That means that it may,
fortuitously, work exactly as expected; but this is no guarantee that it
works on any other compiler.

You may get different results if you add a variable to myclass and access
it from func(); you may not. Either way, you are correct, this code is
wrong, but the compiler may not be able to warn you about it.

Philip

i tried it in microsoft cl 6.0, 7.0 and g++ (suprisingly same
behaviour). all the three give the same result. if its undefined, then
there must be some variations in the output,
No. "Undefined" means that nothing is required. Not even that every compiler
behaves differently.
but its the same. i am really confused.
Why? It's simple. If you invoke undefined behavior, don't expect any specifc
or unspecific behavior. Just don't expect anything.

Aug 18 '06 #8

"Thomas J. Gritzan" <Ph*************@gmx.deskrev i meddelandet
news:ec**********@newsreader2.netcologne.de...
hs******@gmail.com schrieb:
>Consider the below code snippet:
[snip]
>int main(void) {
myclass *obj = new myclass();
delete obj;
obj = NULL; // obj = (myclass*)0;
obj->func(); //..............must be a crash..... but works fine
return 0;
}

i tried the above code in Microsoft compiler 12.0, 13.0 and g++.

Where did you get that compiler? MS C++ is at version 8.0.
No, it's the Visual Studio that is at version 8.0 (or 2005), using the
interesting scheme 1, 2, oops, 4, etc.

The current C++ compiler is at version 14.0, counting its ancestry all
the way back to the very first (non-Visual) MS C compiler, version 3.0
(don't ask :-).
To be somewhat on topic, I must also add that undefined behaviour
doesn't at all mean "must crash", as other posters have pointed out.
The really nasty result is "seems to work".
Bo Persson


Aug 18 '06 #9

hs******@gmail.com wrote:
Consider the below code snippet:

#include <iostream>
using namespace::std;

class myclass
{
public:
myclass() {
cout << "constructor" << endl;
}
~myclass() {
cout << "destructor" << endl;
}
void func() {
cout << "func" << endl;
}
};

int main(void) {
myclass *obj = new myclass();
....should be...
myclass* obj = new myclass;
delete obj;
obj = NULL; // obj = (myclass*)0;
obj->func(); //..............must be a crash..... but works fine
return 0;
}

i tried the above code in Microsoft compiler 12.0, 13.0 and g++.
the code doesnt crash and the output will be like
constructor
destructor
func

i really dont know how when obj is null, obj->func() is valid and not
crashing ?????????????/
Its undefined behaviour. Meaning that the result can't be guarenteed.
Undefined behaviour is often not a crash. Yet if you understand and
apply the concepts - UB is an important subject because
just_because_it_works does not mean its valid.

The only reason you never saw the "crash" is because the func() member
function isn't doing any work. Don't forget that the 'this' parameter
is passed to all non-const member functions. The fact that func() fails
to generate an access diagnostic is only because the obj's internals
are not being accessed.
Consider:

class myclass
{
int m_n;
public:
myclass() : m_n( 0 )
{
std::cout << "constructor" << std::endl;
}
~myclass()
{
std::cout << "destructor" << std::endl;
}
void func()
{
std::cout << "func where m_n = " << m_n << std::endl;
}
};

The above class now does generate a crash when the zapped obj's access
is attempted...
The fact that the original did not crash is irrelevent, its still UB.
Undefined behaviour is about concepts, not results.

Aug 19 '06 #10
On Sat, 19 Aug 2006 01:07:00 +0200, "Bo Persson" <bo*@gmb.dkwrote in
comp.lang.c++:
>
"Thomas J. Gritzan" <Ph*************@gmx.deskrev i meddelandet
news:ec**********@newsreader2.netcologne.de...
hs******@gmail.com schrieb:
Consider the below code snippet:
[snip]
int main(void) {
myclass *obj = new myclass();
delete obj;
obj = NULL; // obj = (myclass*)0;
obj->func(); //..............must be a crash..... but works fine
return 0;
}

i tried the above code in Microsoft compiler 12.0, 13.0 and g++.
Where did you get that compiler? MS C++ is at version 8.0.

No, it's the Visual Studio that is at version 8.0 (or 2005), using the
interesting scheme 1, 2, oops, 4, etc.

The current C++ compiler is at version 14.0, counting its ancestry all
the way back to the very first (non-Visual) MS C compiler, version 3.0
(don't ask :-).
Since you opened the off-topic can of worms, MS C compiler versions
prior to 3.0 were repackaged version of Lattice C.

I made a good living for quite a few years with Lattice C 2.14.

--
Jack Klein
Home: http://JK-Technology.Com
FAQs for
comp.lang.c http://c-faq.com/
comp.lang.c++ http://www.parashift.com/c++-faq-lite/
alt.comp.lang.learn.c-c++
http://www.contrib.andrew.cmu.edu/~a...FAQ-acllc.html
Aug 19 '06 #11
Thomas J. Gritzan schrieb:
hs******@gmail.com schrieb:
>Consider the below code snippet:
[snip]
>int main(void) {
myclass *obj = new myclass();
delete obj;
obj = NULL; // obj = (myclass*)0;
obj->func(); //..............must be a crash..... but works fine
return 0;
}

i tried the above code in Microsoft compiler 12.0, 13.0 and g++.

Where did you get that compiler? MS C++ is at version 8.0.
I guess the OP meant the macro _MSC_VER which the compiler sets to
1200 for MSVC++ 6
1300 for version 7.0 (.NET 2002)
1310 for version 7.1 (.NET 2003)
1400 for version 8.0 (2005)

Maett
Aug 19 '06 #12
Salt_Peter wrote:
>int main(void) {
myclass *obj = new myclass();

...should be...
myclass* obj = new myclass;
Why?
>i really dont know how when obj is null, obj->func() is valid and not
crashing ?????????????/

Its undefined behaviour. Meaning that the result can't be guarenteed.
Undefined behaviour is often not a crash. Yet if you understand and
apply the concepts - UB is an important subject because
just_because_it_works does not mean its valid.

The only reason you never saw the "crash" is because the func() member
function isn't doing any work. Don't forget that the 'this' parameter
is passed to all non-const member functions. The fact that func() fails
to generate an access diagnostic is only because the obj's internals
are not being accessed.
However, this might be the reason (and typically is), but as you write
above, you can't rely on that, because it's undefined behavior.

Aug 20 '06 #13

Rolf Magnus wrote:
Salt_Peter wrote:
int main(void) {
myclass *obj = new myclass();
...should be...
myclass* obj = new myclass;

Why?
Why not? Since the ctor is a default ctor?
>
i really dont know how when obj is null, obj->func() is valid and not
crashing ?????????????/
Its undefined behaviour. Meaning that the result can't be guarenteed.
Undefined behaviour is often not a crash. Yet if you understand and
apply the concepts - UB is an important subject because
just_because_it_works does not mean its valid.

The only reason you never saw the "crash" is because the func() member
function isn't doing any work. Don't forget that the 'this' parameter
is passed to all non-const member functions. The fact that func() fails
to generate an access diagnostic is only because the obj's internals
are not being accessed.

However, this might be the reason (and typically is), but as you write
above, you can't rely on that, because it's undefined behavior.
Its not a question of relying on it. I'm proving that its UB by showing
that an instance of the class is in fact not being accessed, regardless
of the result(s). I'm trying to say: "don't let the result influence
the code's validity". Moreover, i've explained why its UB, not "its UB
cause we said so".

I wish i could find a better word than "concept", maybe "this
particular sequence of events"?

Surely, the concept here is far more important than the result, its the
concept, not the result, that is UB. The language does not dictate that
there is only way good way to code a sequence of events. I think its
far more usefull for the OP to grab the meaning of UB literally. The
English language describes it perfectly : its undefined behaviour,
nothing more, nothing less. Looking for UB should be a tool for the
programmer to write better code, not a detriment nor a dark, mysterious
methodology.

So yes: its UB. But the question is: Why is it UB?

Aug 22 '06 #14
<hs******@gmail.comwrote in message
news:11**********************@i42g2000cwa.googlegr oups.com...
Consider the below code snippet:

#include <iostream>
using namespace::std;

class myclass
{
public:
myclass() {
cout << "constructor" << endl;
}
~myclass() {
cout << "destructor" << endl;
}
void func() {
cout << "func" << endl;
}
};

int main(void) {
myclass *obj = new myclass();
delete obj;
obj = NULL; // obj = (myclass*)0;
obj->func(); //..............must be a crash..... but works fine
return 0;
}

i tried the above code in Microsoft compiler 12.0, 13.0 and g++.
the code doesnt crash and the output will be like
constructor
destructor
func

i really dont know how when obj is null, obj->func() is valid and not
crashing ?????????????/

anybody has an idea about it ??????????
Yes. It's just the implementation. Lets take a look at your calls one by
one.

myclass* obj = new myclass();
This makes obj a pointer to myclass and allocates the memory for it, which
runs the constructor.

delete obj;
This runs the destructor for MyClass and releases the memory.

obj = NULL;
This makes the obj point to nothing.

obj->func();
Okay, so what happens here? The compiler will call the function func()
(which there is only one copy of for no matter how many instances of
MyClass), which gets passed the address of obj (NULL in this case) as the
this pointer.
func() is run, and simply consists of a cout statement, which works.

If you have your func() attempt to output a variable located in MyClass,
however you will get a memory read error (sig fault on linux, memory
exception reading location 0x0000XXXX in windows).

If you do not set
obj = NULL;
it may appear to work sometimes because the memory hasn't been allocated and
changed by another object yet, but othertimes it may give you bad output or
other errors (depending on if another object has allocated the memory and
changed it, or perhaps the page the memory is on has been swapped out
because no object is using that memory, etc..).

Notice, I am only explaining *why* it did not crash for you. I am not
saying you should do this. This is a Bad Idea. But I find that
understanding what is going on beneight the covers sometimes helps me
understand code better.
Aug 22 '06 #15

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: Subhash | last post by:
Hello, I am trying to generate dynamic graphics using the GD library and TTF fonts. The resulting image shows up fine. But in the apache error_log file the following lines are appended: child...
0
by: Russell | last post by:
Hello everybody, I'm the administrator of our network and we have a problem with our Windows server 2003 standard. Recently I've installed the server on our network and promoted it to domain...
6
by: mandir_wahin_banayenge | last post by:
Any suggestions welcome. Sorry if google groups screws up the formatting. TIA, MWB #include <iostream> #include <list> using namespace std;
0
by: Ludovic Launer | last post by:
Just received a new computer. VS2003 works fine with my application, but when trying to create a new asp.net web application ti jsut crahsed without any error message ! I tried to: uninstall...
8
by: The Natural Philosopher | last post by:
This is so weird. What I am trying to do is to upload files and stuff them in a mysql database. Everything works except the file content is zero. using the load_file command from mysql...
3
by: Adhal | last post by:
Hi, I am using remoting to pass in parameters from new launches of an application. So basically I have only one instance of the application and I am using remoting to pass the parameters. ...
0
by: aboutjav.com | last post by:
Hi, I need some help. I am getting this error after I complete the asp.net register control and click on the continue button. It crashed when it tries to get it calls this Profile property ...
8
by: Pallav singh | last post by:
#include<iostream.h> #include<memory.h> #include<string.h> // product class Pizza { private : std::string Topping;
1
by: raghulvarma | last post by:
Hai friends, I need to know what would happen when my IIS gets crashed? what would happen to all the projects present inside it?How should I rectify that?What should I do when I am...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.