473,656 Members | 2,871 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Why does this not fail?

Even if "a" is NULL in the assignment below, this assignment does not
cause any AV:

SOME_PTR * someVar = (SOME_PTR *) a->b;
But something like this will cause an AV because "someVar" is NULL:

if (someVar->someType == 1)
{

}
Why does the first assignment not cause any access violation?

Aug 23 '06 #1
11 1565
In article <11************ **********@74g2 000cwt.googlegr oups.com>,
<sg****@gmail.c omwrote:
>Even if "a" is NULL in the assignment below, this assignment does not
cause any AV:
>SOME_PTR * someVar = (SOME_PTR *) a->b;
>But something like this will cause an AV because "someVar" is NULL:
>if (someVar->someType == 1)
{
}
>Why does the first assignment not cause any access violation?
Chance.

Derefencing a NULL pointer only results in an access violation
when you are lucky. The rest of the time, it does something or other
that is usually much harder to detect.
--
"It is important to remember that when it comes to law, computers
never make copies, only human beings make copies. Computers are given
commands, not permission. Only people can be given permission."
-- Brad Templeton
Aug 23 '06 #2
sg****@gmail.co m writes:
Even if "a" is NULL in the assignment below, this assignment does not
cause any AV:

SOME_PTR * someVar = (SOME_PTR *) a->b;
But something like this will cause an AV because "someVar" is NULL:

if (someVar->someType == 1)
{

}
Why does the first assignment not cause any access violation?
Either way, the behavior is undefined, so anything is actually
allowed to happen. But I suppose your real question is why the
undefined behavior manifests this way. My first thought is that
the former code doesn't actually do anything with the value that
it obtains, so the compiler is probably optimizing it out
entirely, not dereferencing the pointer at all.
--
"The way I see it, an intelligent person who disagrees with me is
probably the most important person I'll interact with on any given
day."
--Billy Chambless
Aug 23 '06 #3
I think since we are not accessing NULL memory, we will get the address
of "b", even if "a" is NULL.

What about this:

&( ((type *)0) -field)

There is no problem here too. I am yet to get a satisfactory answer.

Aug 23 '06 #4

sg****@gmail.co m wrote:
Even if "a" is NULL in the assignment below, this assignment does not
cause any AV:

SOME_PTR * someVar = (SOME_PTR *) a->b;
What is the struct declaration like? In your case It's likely field
"b" is many kilobytes from the start of the struct. Most OS's map the
lower few K of memory to "invalid", so that catches NULL references,
and a lot of NULL->field references. But if a field is far enough into
the structure, it may map into valid memory addresses. And then a->b
might ne a valid read reference.

is NULL:
>
if (someVar->someType == 1)

Yep, if someType is in the first few K of the struct, it is likely to
get caught as a bad address.

Aug 23 '06 #5
I have seen at quite a few places that offsetof() is coded something
like

#define offsetof(type, mem) ((size_t)((char *)&((type *)0)->mem - (char
*)(type *)0))

Now, not getting into other issues with the code (portability etc), if
we see, we have null pointer dereferencing here. How is this allowed?

Aug 23 '06 #6
In article <11************ **********@75g2 000cwc.googlegr oups.com>,
<sg****@gmail.c omwrote:
>I think since we are not accessing NULL memory, we will get the address
of "b", even if "a" is NULL.
Please quote enough context so that people know what you are
referring to.

Your reply is with respect to a->b where a is NULL.

a->b is the same as (*a).b by definition. b must therefore be
a field name within the structure type associated with *a.
As b is a field name and not a variable, b has no address of its
own, so your analysis cannot be correct.

In considering (*a).b with a being NULL, you should understand
that the C standards say that doing this is not allowed and that
the results are undefined. The standards do not say that the program
must crash: crashing is one of the allowed options, as is doing
something else completely like accessing an I/O register or loading
a random number. Crashing is relatively easy to track down; the
other possibilities might lurk undetected for decades.

One of the allowed behaviours for (*a).b with a being NULL, is to
calculate the distance of the field b relative to the begining
of the structure, and then attempt to access a memory location that
much further along from whatever bit pattern NULL happens to be,
which often -happens- to be the all-zero bit pattern. For example,
if the field b happens to start 84 bytes from the beginning of the
structure then the code might try accessing location 0+84 . And
that just might happen to work, because there just might happen to
be valid and accessible memory at that location. Or it might happen
to crash if the system knows there is no memory there. Or it might
happen to return 0's, if the memory system knows there is no memory
there and automatically substitutes 0's. I've seen all of these
behaviours on real systems.

>What about this:
>&( ((type *)0) -field)
>There is no problem here too. I am yet to get a satisfactory answer.
This is slightly different in that the address of (*0).field is
being taken without the content of (*0).field being needed.
This does not need to go to the memory hardware for lookup, so
*some* systems would treat the above as calculating the offset of
the field relative to the beginning of the structure. It doesn't
really calculate that, though, as it is the wrong type (address
instead of offset).

According to the C standards, the -operator is only valid when
its left side is a pointer to an object, and 0 (or NULL) are
defined as pointing to NO object. Therefore the code
does not have a defined result according to the C standards.
It isn't uncommon to see the code in the implementation of
offset(), but that's because the implementation is allowed to take
advantage of internal knowledge of the operating system, and so
is allowed to do things that C programmers cannot safely do in
user programs. The code is *not* portable. (But as I discussed
above, systems are not -required- to give an error when they
encounter it.)
--
"It is important to remember that when it comes to law, computers
never make copies, only human beings make copies. Computers are given
commands, not permission. Only people can be given permission."
-- Brad Templeton
Aug 23 '06 #7
"Ancient_Hacker " <gr**@comcast.n etwrites:
sg****@gmail.co m wrote:
>Even if "a" is NULL in the assignment below, this assignment does not
cause any AV:

SOME_PTR * someVar = (SOME_PTR *) a->b;

What is the struct declaration like? In your case It's likely field
"b" is many kilobytes from the start of the struct. Most OS's map the
lower few K of memory to "invalid", so that catches NULL references,
and a lot of NULL->field references. But if a field is far enough into
the structure, it may map into valid memory addresses. And then a->b
might ne a valid read reference.
Really? On what OSes is the second page of virtual address space
commonly mapped?
--
int main(void){char p[]="ABCDEFGHIJKLM NOPQRSTUVWXYZab cdefghijklmnopq rstuvwxyz.\
\n",*q="kl BIcNBFr.NKEzjwC IxNJC";int i=sizeof p/2;char *strchr();int putchar(\
);while(*q){i+= strchr(p,*q++)-p;if(i>=(int)si zeof p)i-=sizeof p-1;putchar(p[i]\
);}return 0;}
Aug 23 '06 #8


sg****@gmail.co m wrote On 08/23/06 15:07,:
I have seen at quite a few places that offsetof() is coded something
like

#define offsetof(type, mem) ((size_t)((char *)&((type *)0)->mem - (char
*)(type *)0))

Now, not getting into other issues with the code (portability etc), if
we see, we have null pointer dereferencing here. How is this allowed?
The answer is inseparably bound with the "other issues"
you don't want to get into.

Briefly, the implementation can use all the non-portable
tricks and gimmicks it feels like, so long as they produce
the effect the Standard requires. The implementation does
not need to be portable to other implementations . The Frobozz
Magic C compiler is not required to work as advertised if you
try to run it on the DeathStation 9000. The implementation
doesn't even need to be written in C at all.

... and that's why dodgy implementations of offsetof() are
allowed: because they're part of the implementation, not
part of the user code.

--
Er*********@sun .com

Aug 23 '06 #9
In article <87************ @benpfaff.org>,
Ben Pfaff <bl*@cs.stanfor d.eduwrote:
>"Ancient_Hacke r" <gr**@comcast.n etwrites:
>Most OS's map the
lower few K of memory to "invalid", so that catches NULL references,
and a lot of NULL->field references. But if a field is far enough into
the structure, it may map into valid memory addresses.
>Really? On what OSes is the second page of virtual address space
commonly mapped?
Ancient_Hacker made no reference to a "page" of virtual memory.
His reference was to "the lower few K", which is sufficiently
imprecise to cover paged and non-paged memory models and to cover
protected memory that might be 1 page long, 16 pages long, 42 pages
long...
But to answer your question very specifically:

Silicon Graphics IRIX, starting from some version starting in 4.x,
through to version 6.5.22.

If memory serves me, it was IRIX 6.4 that introduced the models for
which the second page of virtual adress space was NOT commonly mapped.
It wasn't a matter that the addresses were no longer used: what
happened is that the page size got larger for newer hardware models,
requiring that the mapped memory be accessed via the first page (which
was now big enough to cover that address space). IRIX 6.4 -only-
supported models that referenced the memory via the first virtual page;
IRIX 6.5 was a general purpose OS that supported both models that used
the second virtual page for the needed addresses and models that used
the first {larger} virtual page for the same addresses. However, after
6.5.22, support was dropped for all the hardware that used the smaller
page size.

In IRIX 4 through 6.5.22 on models that supported the smaller page
size, the first virtual page of memory is flagged as allowing
no access (no read, no write, no execute), but the second virtual
page of memory was read and write because it was used for SGI's GL
graphics subsystem. In IRIX 6.4 and in IRIX 6.5 on the models with
the larger virtual page, the GL addresses are part of the {larger} first
page; as read and write were required for GL graphics, this had
the size effect of unprotecting memory address 0. If I recall
correctly, the locations near there are initialized to 0... and Yes, they
are writable :(
--
"No one has the right to destroy another person's belief by
demanding empirical evidence." -- Ann Landers
Aug 23 '06 #10

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

Similar topics

14
3031
by: Dave Murray | last post by:
New to Python question, why does this fail? Thanks, Dave ---testcase.py--- import sys, urllib, htmllib def Checkit(URL): try: print "Opening", URL
2
1997
by: John | last post by:
The following code works OK in IE 6.0 but does not work in Netscape 7. The image does not shift when one scrolls down but stays stationary in Netscape. Please help Thank you John function moveImage(e){ //shift image according to scroll
24
3797
by: David Mathog | last post by:
If this: int i,sum; int *array; for(sum=0, i=0; i<len; i++){ sum += array; } is converted to this (never mind why for the moment):
19
2102
by: James Harris | last post by:
My K&R 2nd ed has in the Reference Manual appendix, A7.4.8 sizeof yields the number of BYTES required to store an object of the type of its operand. What happens if C is running on a machine that addresses larger words only? Shouldn't sizeof be defined to return the smallest number of 'storage units' required to store an object of the type of its operand? As a general point, is there a guide to what aspects of C would fail if run on a...
16
4971
by: lawrence k | last post by:
I've a file upload script on my site. I just now used it to upload a small text document (10k). Everything worked fine. Then I tried to upload a 5.3 meg Quicktime video. Didn't work. I've set the POST limit in php.ini to 8 megs. What reasons, other than the POST limit, would a large upload fail?
10
2373
by: Gunnar G | last post by:
I'm having problem reading from the beginning of a file. Here is the code (more or less) ifstream codefin; ofstream codefout; while (not_annoyed)
9
2145
by: David Thielen | last post by:
Hi; I am sure I am missing something here but I cannot figure it out. Below I have a program and I cannot figure out why the xpath selects that throw an exception fail. From what I know they should work. Also the second nav.OuterXml appears to also be wrong to me. Can someone explain to me why this does not work? (This is an example from a program we have where xpath can be entered in two parts so we have to be able
4
1478
by: Kai Grossjohann | last post by:
I wrote a test case that depends on a certain file existing in the environment. So, I guess I should test that the file exists in the setUp method. But what if it doesn't exist? How do I fail in that case? I would like to emit an error message explaining what is wrong. tia, Kai
19
4182
by: Angus | last post by:
I have a socket class CTestClientSocket which I am using to simulate load testing. I create multiple instances of the client like this: for (int i = 0; i < 5; i++) { CTestClientSocket* pTemp = new CTestClientSocket(this, ip, port); pTemp->Connect(); m_collClients.push_back(pTemp);
3
1551
by: ChrisEdgemon | last post by:
I'd like to implement a subclass of string that works like this: True False True My best attempt for something like this is: class MyString(str): def __init__(self, seq):
0
8382
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
8297
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
8717
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8498
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
6162
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
4150
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...
1
2726
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1930
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1600
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.