473,626 Members | 3,276 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Able to call member function with a pointer assigned NULL

Hi,

I have a code as follows:

class A
{
public:
void print(){cout << "Magic" << endl;}
};

int main()
{
A* ptrA = NULL;
ptrA->print();
}
The out put is given as Magic.

I wanted to know why is it happening.
In case i add one data member to the class say int i;
then this code will not work.

Can any body explain why?

Thanks

Apr 11 '06 #1
8 3337

nsharm...@gmail .com wrote:
Hi,

I have a code as follows:

class A
{
public:
void print(){cout << "Magic" << endl;}
};

int main()
{
A* ptrA = NULL;
ptrA->print();
}
The out put is given as Magic.

I wanted to know why is it happening.
In case i add one data member to the class say int i;
then this code will not work.

Can any body explain why?


Calling a function on an invalid pointer illicits undefined behavior.

Apr 11 '06 #2
ns*******@gmail .com wrote:
class A
{
public:
void print(){cout << "Magic" << endl;}
};

int main()
{
A* ptrA = NULL;
ptrA->print();
}
The out put is given as Magic.

I wanted to know why is it happening.


You have UB, which means anything can happen.

Member functions are basically regular functions with a hidden "this"
parameter, so in a situation like you gave above, it is possible that it
will work. However, if you add a data member and try to access it, then
you will almost certainly get a crash.

Do not rely on this behavior. Dereferencing a null pointer is always a
bad idea.

--
Marcus Kwok
Replace 'invalid' with 'net' to reply
Apr 11 '06 #3
Marcus Kwok wrote:
ns*******@gmail .com wrote:
class A
{
public:
void print(){cout << "Magic" << endl;}
};

int main()
{
A* ptrA = NULL;
ptrA->print();
}
The out put is given as Magic.

I wanted to know why is it happening.


You have UB, which means anything can happen.

Member functions are basically regular functions with a hidden "this"
parameter, so in a situation like you gave above, it is possible that it
will work. However, if you add a data member and try to access it, then
you will almost certainly get a crash.

Do not rely on this behavior. Dereferencing a null pointer is always a
bad idea.


However, could you tell us what platform and compiler this was on so
that we can easily hold it up as an example of how undefined behaviour
can blow up? (I haven't seen this particular type of undefined
behaviour fail before, unless you attempt to reference a member variable
from within the method that was called.)
Apr 11 '06 #4
Andre Kostur <nn******@kostu r.net> wrote:
Marcus Kwok wrote:
ns*******@gmail .com wrote:
class A
{
public:
void print(){cout << "Magic" << endl;}
};

int main()
{
A* ptrA = NULL;
ptrA->print();
}
The out put is given as Magic.


You have UB, which means anything can happen.

Member functions are basically regular functions with a hidden "this"
parameter, so in a situation like you gave above, it is possible that it
will work. However, if you add a data member and try to access it, then
you will almost certainly get a crash.

Do not rely on this behavior. Dereferencing a null pointer is always a
bad idea.


However, could you tell us what platform and compiler this was on so
that we can easily hold it up as an example of how undefined behaviour
can blow up? (I haven't seen this particular type of undefined
behaviour fail before, unless you attempt to reference a member variable
from within the method that was called.)


Honestly, it works on all four systems I just tried it on, but that's
the problem with UB: It can do anything, including exactly what you
expect it to do. However, I will stick to my stance that relying on UB
is generally not a good idea.

--
Marcus Kwok
Replace 'invalid' with 'net' to reply
Apr 11 '06 #5
I know that it is UB. I was just curious how that function is executed
thru a NULL pointer.
It seems that this function is as good as a non-member function
executing at its own and do not require any valid pointer.

but whenever we add a data member it simply crashes.

I just wanted to know what causes that crash and why it is necessary to
add a data member to re-produce that crash.

Thanks,

Marcus Kwok wrote:
Andre Kostur <nn******@kostu r.net> wrote:
Marcus Kwok wrote:
ns*******@gmail .com wrote:
class A
{
public:
void print(){cout << "Magic" << endl;}
};

int main()
{
A* ptrA = NULL;
ptrA->print();
}
The out put is given as Magic.

You have UB, which means anything can happen.

Member functions are basically regular functions with a hidden "this"
parameter, so in a situation like you gave above, it is possible that it
will work. However, if you add a data member and try to access it, then
you will almost certainly get a crash.

Do not rely on this behavior. Dereferencing a null pointer is always a
bad idea.


However, could you tell us what platform and compiler this was on so
that we can easily hold it up as an example of how undefined behaviour
can blow up? (I haven't seen this particular type of undefined
behaviour fail before, unless you attempt to reference a member variable
from within the method that was called.)


Honestly, it works on all four systems I just tried it on, but that's
the problem with UB: It can do anything, including exactly what you
expect it to do. However, I will stick to my stance that relying on UB
is generally not a good idea.

--
Marcus Kwok
Replace 'invalid' with 'net' to reply


Apr 11 '06 #6
ns*******@gmail .com wrote:
I know that it is UB. I was just curious how that function is executed
thru a NULL pointer.
It seems that this function is as good as a non-member function
executing at its own and do not require any valid pointer.

but whenever we add a data member it simply crashes.
Back to my curiosity question of what platform and compiler is this?
Just so we (clc++) can use it as an example of where this specific
instance of UB crashes the program.
I just wanted to know what causes that crash and why it is necessary to
add a data member to re-produce that crash.


Not to sound snarky, but why do you care? Since attempting to call a
method through a NULL pointer invokes Undefined Behviour, regardless of
whatever the content of your class is, why does it matter when it
crashes? (I explained why _I_ want to know when this crashes....)

However, the nutshell version (and definitely implementation-specific)
is that in most cases the compiler converts function calls of the form:

obj->method(param 1, param2);

into something resembling:

method(obj, param1, param2);
Inside method(), the first parameter(obj) gets assigned to the "this"
pointer, and the rest of the parameters are dealt with as normal.

However, simply adding a member variable "shouldn't" cause anything to
blow up unless you attempt to access that variable within the method.
Up to that point you haven't (necessarily) caused the program to attempt
to dereference the NULL pointer. If you tried to access the member
variable:

a = 4;

That would be "converted" to:

this->a = 4;

This would have to dereference the NULL pointer, and attempt to assign 4
into whatever appropriate memory location relative to NULL that a
happens to lie on (and is likely not writable memory...).

And more things start coming into play if method() happens to be virtual....

Again, all of this is conjecture, and compiler implementors can
implement all of this in whatever way they choose. It all boils down
to: Calling methods through a NULL pointer is Undefined Behaviour.

Apr 11 '06 #7
On 2006-04-11, ns*******@gmail .com <ns*******@gmai l.com> wrote:
[...]
class A
{
public:
void print(){cout << "Magic" << endl;}
};

int main()
{
A* ptrA = NULL;
ptrA->print();
} I know that it is UB. I was just curious how that function is executed
thru a NULL pointer. It seems that this function is as good as a non-member function
executing at its own and do not require any valid pointer.

but whenever we add a data member it simply crashes.

I just wanted to know what causes that crash and why it is necessary to
add a data member to re-produce that crash.
[...]


The function print() is non-virtual, and so the compiler doesn't need to
dereference ptrA to find the function print. It would be generating
unnecessarily inefficient code if it did. So the call to ptrA->print()
doesn't actually require dereferencing ptrA at all. It's just a call to
A::print() with the parameter 0 in "this".

Of course, as soon as you access a data member in the body of print(),
the program will access 0->data_ and that's when it'll very likely
crash.

I think it probably is defined that a class with no virtual functions
has no vtable.

Still calling a method of 0 probably is undefined behaviour anyway.
Apr 18 '06 #8

Ben C wrote:
I think it probably is defined that a class with no virtual functions
has no vtable.
If by "defined" you mean "required by the standard" then, no that's not
defined. The standard doesn't say anything about vtables at all. I'd be
surprised if any compiler that elected to implement polymorphism
through vtables also put a vtable in a class with no virtual functions
though.
Still calling a method of 0 probably is undefined behaviour anyway.


It's definitely undefined behaviour. Always.

Gavin Deane

Apr 19 '06 #9

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

Similar topics

2
11516
by: Devrobcom | last post by:
Hi I know that this is not the Lint forum, but I get some Lint warnings when setting my pointers to NULL. And the problem is I don't know howto cast a function ptr the right way. typedef int FP(char*, char*); FP *pfp; pfp = NULL; --error 64: (Error -- Type mismatch (assignment) (ptrs to void/nonvoid))
54
7825
by: Neo | last post by:
Hi Folks, I've a simple qestion related to dynamic memory allocation in C here is the code: #include <stdio.h> int main() {
46
2241
by: TTroy | last post by:
Hi, I'm just wondering why people/books/experts say "the function returns a pointer to.." or "we have to send scanf a pointer to.." instead of "the function returns the address of.." or "we have to send scanf the address of.." Isn't the lvalue called a POINTER TO and the (r)value called the ADDRESS OF?
16
10367
by: Abhishek | last post by:
why do I see that in most C programs, pointers in functions are accepted as: int func(int i,(void *)p) where p is a pointer or an address which is passed from the place where it is called. what do you mean by pointing to a void and why is it done? Aso, what happens when we typecast a pointer to another type. say for example int *i=(char *)p; under different situations? I am kind of confused..can anybody clear this confusion by clearly...
5
3329
by: Frederick Gotham | last post by:
If we have a simple class such as follows: #include <string> struct MyStruct { std::string member; MyStruct(unsigned const i) {
27
3109
by: Terry | last post by:
I am getting the following warning for the below function. I understand what it means but how do I handle a null reference? Then how do I pass the resulting value? Regards Warning 1 Function 'Dec2hms' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used.
12
540
by: WaterWalk | last post by:
Hello. I am rather confused by the type of a pointer to class data member. Many c++ texts say that pointer to data member has a special syntax. For example the following class: class MyClass { public: int n; }; The pointer to MyClass.n shall be defined like this:
12
7191
by: Rahul | last post by:
Hi Everyone, I have the following code and i'm able to invoke the destructor explicitly but not the constructor. and i get a compile time error when i invoke the constructor, why is this so? class Trial { public: Trial() {
4
3851
by: Ty | last post by:
Hello all, I am creating a web site with Visual Stuido 2008. I am trying to use a java script file to create a busybox for login from this page http://blogs.crsw.com/mark/articles/642.aspx. I am using a master page senerio. The erro I'm getting is 'busyBox' is not a member of 'ASP.login2_aspx'
0
8203
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8711
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
8368
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,...
1
6125
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
5576
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
4094
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...
0
4206
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1815
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1515
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.