473,804 Members | 3,757 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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

Consider the below code snippet:

#include <iostream>
using namespace::std;

class myclass
{
public:
myclass() {
cout << "constructo r" << 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(); //..............m ust 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
14 1593
On Sat, 19 Aug 2006 01:07:00 +0200, "Bo Persson" <bo*@gmb.dkwrot e 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(); //..............m ust 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.l earn.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(); //..............m ust 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.goo glegroups.com.. .
Consider the below code snippet:

#include <iostream>
using namespace::std;

class myclass
{
public:
myclass() {
cout << "constructo r" << 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(); //..............m ust 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
2570
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 pid 29141 exit signal Segmentation fault (11) MMCACHE: PHP crashed on opline 14 of imagettfbbox() at test.php:13 Seems like it might be a GD library problem but I am not sure. Any
0
1038
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 controller. Everything works fine. Our R&D department is developing a program that's created with c-sharp and runs in .NET (I hope my explanation is correct, because I'm not familiair with programming!)
6
1197
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
948
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 framework 1.1 / reinstall uninstall vs2003 / reinstall aspnet_regiis.exe -i No success It says "creating web application" and then you can see the animation with
8
3882
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 command line as 'root' works and i can download the inserted file ok.
3
3747
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. The problem is as follows: I can remote call the first few times, but then I get the "No connection could be made because target machine actively refused it 127.0.0.1:8084"
0
2011
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 ((string)(this.GetPropertyValue("Address1")));
8
1518
by: Pallav singh | last post by:
#include<iostream.h> #include<memory.h> #include<string.h> // product class Pizza { private : std::string Topping;
1
1979
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 asked to rectify the IIS which is crashed and the web page only specifies "Server Crashed" and no other information is provided? Could you plz specify a good link where I could get more information on IIS? Thanks Raghul
0
9706
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10571
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10317
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9143
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7615
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 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 a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6851
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5520
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
3815
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2990
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.