473,698 Members | 2,058 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

De-referencing NULL

#include <stdio.h>

int
main (void) {
char *p = NULL;
printf ("%c\n", *p);
return 0;
}

This snippet prints 0(compiled with DJGPP on Win XP). Visual C++ 6.0
compiles the program with diagnostics and the program crashes when
ran. gcc on Linux gives SEGMENTATION FAULT.

This looks like a bug with DJGPP. NULL can have different
representations but how come the compiler allows de-referencing NULL
without any compile time or run-time errors?

P.S : I am not discussing DJGPP. I just want to know if this behaviour
is OK with C specs?
Aug 4 '08
28 1866
santosh wrote:
rahul wrote:
>#include <stdio.h>

int
main (void) {
char *p = NULL;
printf ("%c\n", *p);
return 0;
}

This snippet prints 0(compiled with DJGPP on Win XP). Visual C++ 6.0
compiles the program with diagnostics and the program crashes when
ran. gcc on Linux gives SEGMENTATION FAULT.

This looks like a bug with DJGPP. NULL can have different
representation s but how come the compiler allows de-referencing NULL
without any compile time or run-time errors?

I have already provided the reason why no compile-time diagnostics are
required. As for runtime diagnostics/exceptions, note that the
segfaults you are getting from Windows XP (compiled with MSVC) and
Linux are a response of the operating system. DJGPP on the other hand
is designed to produce programs that run under DOS, which does not
have memory protection and hence fails to trap the access to memory
address zero.

All the above is information beyond the scope of the C Standard, which
by categorising the behaviour as undefined, allows different
implementations to do whatever makes the most sense for them and
avoids defining this complex issue. If it had defined the behaviour in
any manner, there would have been some systems which would then have
had to emulate this behaviour and hence suffer considerable
performance and implementation problems.

This is merely a special case of C allowing access beyond an object.
And the above is subtly wrong and highly misleading.

A null pointer *cannot* by definition point to anywhere and thus a
deference of a null pointer is always invalid. This has nothing to do
with the hardware or with memory addresses, but is dictated by the
semantics of C. It just so happens that on the vast majority of
implementations the value that a null pointer contains is the same as
the value for memory address zero at a bit level. Thus when a null
pointer is deferenced, the implementation interprets the value as a
memory address and attempts to read it. This is caught under some
systems and not under others.

Conceptually a null pointer is distinct from a pointer containing the
address value zero, but under many flat memory model architectures
their representations are identical and hence, in the absence of any
special interpretation (which becomes cumbersome), deferencing a null
pointer performs the same action as deferencing a pointer containing
address zero.

Recently Harald van Dijk gave an example of an implementation (I think
it was the Tendra C compiler) that interprets a null pointer as having
a value other than zero.

Aug 4 '08 #11
santosh <sa*********@gm ail.comwrites:
[...]
Conceptually a null pointer is distinct from a pointer containing the
address value zero, but under many flat memory model architectures
their representations are identical and hence, in the absence of any
special interpretation (which becomes cumbersome), deferencing a null
pointer performs the same action as deferencing a pointer containing
address zero.
[...]

Sort of -- except that there's not really such a thing as "the address
value zero" in C, at least not in the sense that you mean.

You can *convert* an integer value zero to a pointer type. If the
converted value happens to be a constant expression, the result is a
null pointer value, due to the special-case rule that C uses to define
null pointer constants. If it's a non-constant expression whose
current run-time value is zero, the result of the conversion is
implementation-defined, and may or may not correspond to "the address
value zero" on the underlying system, assuming such a thing is even
meaningful.

This means that converting a value of zero to a pointer type might
yield different results depending on whether the zero value is a
constant expression or not, which is a bit bizarre. But most systems
don't make this distinction because, as santosh said in text I've
snipped, most systems choose to use all-bits-zero as the null pointer
representation, avoiding the need for special-case code to handle the
special-case rule for null pointer constants. On most (but not all)
such systems, attempts to dereference a null pointer are caught with
no additional effort, since 00000000 is not a valid address.

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
Nokia
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Aug 4 '08 #12
Keith Thompson schrieb:
>P.S : I am not discussing DJGPP. I just want to know if this behaviour
is OK with C specs?

The behavior is undefined, which means that any behavior is ok as far
as the standard is concerned.
I've started wondering whether this is a good idea - on architectures
like the AVR, there are indeed memory-mapped I/O registers in the
address space at address 0x00. For instance on an ATmega32, writing to

*((volatile unsigned char*)0x00) = 0x00;

Would set the TWBR (Two Wire Serial Interface Bit Rate Register). Is
this undefined behaviour, too? This would then mean the language is in
some way incompatible with the architecture, which is a really weird thing.

Regards,
Johannes

--
"Wer etwas kritisiert muss es noch lange nicht selber besser können. Es
reicht zu wissen, daß andere es besser können und andere es auch
besser machen um einen Vergleich zu bringen." - Wolfgang Gerber
in de.sci.electron ics <47************ ***********@new s.freenet.de>
Aug 4 '08 #13
>Keith Thompson schrieb:
>The behavior is undefined, which means that any behavior is ok as far
as the standard is concerned.
In article <i6************ @joeserver.home lan.net>
Johannes Bauer <df***********@ gmx.dewrote:
>I've started wondering whether this is a good idea -
It is, in fact, a great idea, precisely because of what you say next.
>on architectures like the AVR, there are indeed memory-mapped I/O
registers in the address space at address 0x00. For instance on an
ATmega32, writing to

*((volatile unsigned char*)0x00) = 0x00;

Would set the TWBR (Two Wire Serial Interface Bit Rate Register). Is
this undefined behaviour, too?
Undefined by the C Standard, yes.

By being left undefined in the C Standard, implementors are allowed
to define it themselves. Implementors working on the ATmega32 can
define (*(volatile unsigned char *)0) as "access the TWBR".

Had the C Standard said "this must trap" or "this must access RAM",
implementors writing implementations for the ATmega32 would *not*
have been able to give you access to the TWBR in this obvious and
simple manner.

Undefined behavior is "bad" in that, if you use it, you lose the
guarantees of the C Standard. But it is "good" in that, by leaving
it undefined, you can use non-"Standard C" in ways guaranteed by
something *other* than the C Standard. There is nothing wrong with
doing this: you just need to know that your guarantees are coming
from "Frobozz Inc ATmega32 C" and not "ISO Standard C".
--
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W) +1 801 277 2603
email: gmail (figure it out) http://web.torek.net/torek/index.html
Aug 4 '08 #14
Chris Torek schrieb:
>I've started wondering whether this is a good idea -

It is, in fact, a great idea, precisely because of what you say next.
Okay, alright, I understood what you wrote. Thank you for your
comprehensive answer!

Regards,
Johannes

--
"Wer etwas kritisiert muss es noch lange nicht selber besser können. Es
reicht zu wissen, daß andere es besser können und andere es auch
besser machen um einen Vergleich zu bringen." - Wolfgang Gerber
in de.sci.electron ics <47************ ***********@new s.freenet.de>
Aug 4 '08 #15
rahul wrote:
>
#include <stdio.h>

int main (void) {
char *p = NULL;
printf ("%c\n", *p);
return 0;
}

This snippet prints 0(compiled with DJGPP on Win XP). Visual C++
6.0 compiles the program with diagnostics and the program crashes
when ran. gcc on Linux gives SEGMENTATION FAULT.

This looks like a bug with DJGPP. NULL can have different
representations but how come the compiler allows de-referencing
NULL without any compile time or run-time errors?

P.S : I am not discussing DJGPP. I just want to know if this
behaviour is OK with C specs?
No, it is not allowable to dereference the NULL pointer. Behaviour
is undetermined. The fact that DJGPP doesn't detect this fault is
a Quality of Implementation detail.

--
[mail]: Chuck F (cbfalconer at maineline dot net)
[page]: <http://cbfalconer.home .att.net>
Try the download section.

Aug 4 '08 #16
In article <i6************ @joeserver.home lan.net>,
Johannes Bauer <df***********@ gmx.dewrote:
>Keith Thompson schrieb:
>>P.S : I am not discussing DJGPP. I just want to know if this behaviour
is OK with C specs?
The behavior is undefined, which means that any behavior is ok as far
as the standard is concerned.

I've started wondering whether this is a good idea - on architectures
like the AVR, there are indeed memory-mapped I/O registers in the
address space at address 0x00. For instance on an ATmega32, writing to

*((volatile unsigned char*)0x00) = 0x00;

Would set the TWBR (Two Wire Serial Interface Bit Rate Register). Is
this undefined behaviour, too?
It is undefined behavior.
>This would then mean the language is in
some way incompatible with the architecture, which is a really weird thing.
Not necessarily incompatible. It is not saying it must be rejected
or that it must fail, it is "just" not telling you what happens.
What it is doing then is leaving the door open to allow you to do it,
of course, along with a compiler for the platform in question.
Since C is not defining it, it's giving you a "fighting chance"
of giving you the rope on machines where you need that rope.
On those where you don't need the rope, it is still there though.
But as in the thread, on those other machines, compilers etc
can set it up for a trap, and so on.
--
Greg Comeau / 4.3.10.1 with C++0xisms now in beta!
Comeau C/C++ ONLINE == http://www.comeaucomputing.com/tryitout
World Class Compilers: Breathtaking C++, Amazing C99, Fabulous C90.
Comeau C/C++ with Dinkumware's Libraries... Have you tried it?
Aug 5 '08 #17
On Mon, 04 Aug 2008 20:42:58 +0200, Johannes Bauer
<df***********@ gmx.dewrote in comp.lang.c:
Keith Thompson schrieb:
P.S : I am not discussing DJGPP. I just want to know if this behaviour
is OK with C specs?
The behavior is undefined, which means that any behavior is ok as far
as the standard is concerned.

I've started wondering whether this is a good idea - on architectures
like the AVR, there are indeed memory-mapped I/O registers in the
address space at address 0x00. For instance on an ATmega32, writing to

*((volatile unsigned char*)0x00) = 0x00;

Would set the TWBR (Two Wire Serial Interface Bit Rate Register). Is
this undefined behaviour, too? This would then mean the language is in
some way incompatible with the architecture, which is a really weird thing.
As others have already mentioned, it is of course undefined behavior,
which is not necessarily a bad thing in all contexts.

But if Atmel moved that register from address 0x00 to 0x01, or 0x08,
or indeed any other address, the result of reading from or writing to
that address would still be undefined. Any access to any hardware
device is completely undefined under the C standard, and that is
exactly as it should be.

--
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.club.cc.cmu.edu/~ajo/docs/FAQ-acllc.html
Aug 5 '08 #18
On 5 Aug 2008 at 1:24, Jack Klein wrote:
On Mon, 04 Aug 2008 20:42:58 +0200, Johannes Bauer
<df*********** @gmx.dewrote in comp.lang.c:
>*((volatile unsigned char*)0x00) = 0x00;

Would set the TWBR (Two Wire Serial Interface Bit Rate Register). Is
this undefined behaviour, too? This would then mean the language is in
some way incompatible with the architecture, which is a really weird thing.

As others have already mentioned, it is of course undefined behavior,
which is not necessarily a bad thing in all contexts.

But if Atmel moved that register from address 0x00 to 0x01, or 0x08,
or indeed any other address, the result of reading from or writing to
that address would still be undefined. Any access to any hardware
device is completely undefined under the C standard, and that is
exactly as it should be.
This is complete nonsense, as you are well aware. The whole point of the
OP's query is that 0 in a pointer context is a null pointer constant,
whereas 1 and 8 are not.

Aug 5 '08 #19
In article <i6************ @joeserver.home lan.net>,
Johannes Bauer <df***********@ gmx.dewrote:
>I've started wondering whether this is a good idea - on architectures
like the AVR, there are indeed memory-mapped I/O registers in the
address space at address 0x00. For instance on an ATmega32, writing to

*((volatile unsigned char*)0x00) = 0x00;

Would set the TWBR (Two Wire Serial Interface Bit Rate Register). Is
this undefined behaviour, too? This would then mean the language is in
some way incompatible with the architecture, which is a really weird thing.
I'm just going to address the last sentence.

You might consider the language incompatible with the architecture if
it said anything about what happened when address 0 was accessed, but
C doesn't do that. There is no necessary connection between C's null
pointer and the architecture's address 0, though they are the same in
most implementations . In particular, there's no reason that

(volatile unsigned char*)0x00

produce the architecture address 0. It could produce, say, 0xffffffff.
The conversion of integers to pointers can involve arbitrary computation,
but null pointers can only be generated from constants, so the compiler
could do or insert code for the necessary conversion.

int x = 0;
(char *)x

is not guaranteed to produce a null pointer.

I doubt that this would be a good idea on balance, though such a compiler
might be useful for certain kinds of debugging.

-- Richard
--
Please remember to mention me / in tapes you leave behind.
Aug 6 '08 #20

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

Similar topics

2
3029
by: grigoo | last post by:
bonjour a tous je me presente a vous::: greg dit le grigoo sur le web ,,etudiant en bioinformatique a montreal et jusqu au cou dans notre language prefere....java. et biojava.. et je suis en un newbee dans ce domaine et me dit que l homme est bien peu de chose voici en definitive mon probleme>>> je construit une classe appele symbolListWithGap. dans celle j y mets un constructeur:::: symbolListWithGap qui recoit
0
1730
by: Laurent Pointal | last post by:
Bienvenue sur la liste Python francophone, hébergée par l'AFUL, ou sur le newsgroup fr.comp.lang.python ("fclp"). Votre abonnement à cette liste de diffusion ou votre lecture de fclp montrent un intérêt pour le langage Python et ce qui tourne autour. Après quelques temps de lecture, vous serez sûrement amené à poster vous aussi un message. Voici quelques conseils d'utilisation, suivi d'une série de liens à partir desquels vous ...
0
463
by: Michael Dyson | last post by:
M. Michael DYSON DIRECTEUR-ADJOINT SOCIÉTÉ DE SÉCURITÉ SARL. TEL.00229 20 21 80 Cotonou République du Bénin Email:michaeldyson2005@latinmail.com Bonjour . Je sais que mon message sera d’une grande surprise quand t-il vous parviendra. Donc, je vous présente toutes mes excuses. Je vous écris sincèrement dans le but d’obtenir votre coopération et votre confiance pouvant
0
2232
by: Alejandro Scomparin | last post by:
FORMULACION, PREPARACION Y EVALUACION ECONOMICA Y FINANCIERA DE PROYECTOS DE TECNOLOGIA INFORMATICA (IT) en la UTN Inicia: 17 de Mayo. 19 hs Dirigido a Esta preparado para gerentes, jefes, líder de proyectos del área de IT de todo tipo de organizaciones, y para profesionales de
0
4289
by: Alejandro Scomparin | last post by:
FORMULACION, PREPARACION Y EVALUACION ECONOMICA Y FINANCIERA DE PROYECTOS DE TECNOLOGIA INFORMATICA (IT) en la UTN Inicia: 17 de Mayo. 19 hs Dirigido a Esta preparado para gerentes, jefes, líder de proyectos del área de IT de todo tipo de organizaciones, y para profesionales de
0
1483
by: gandalf | last post by:
Con motivo del enorme esfuerzo realizado para visitar la ciudad argentina de Córdoba, participar en la Reunión del MERCOSUR, en la clausura de la Cumbre de los Pueblos en la histórica Universidad de Córdoba y en la visita a Altagracia, la ciudad donde vivió el Che en su infancia y unido a esto asistir de inmediato a la conmemoración del 53 aniversario del asalto a los cuarteles Moncada y Carlos Manuel de Céspedes, el 26 de julio de 1953,...
1
1624
by: crow | last post by:
http://www.pagina12.com.ar/diario/elpais/1-72984-2006-09-14.html Por Miguel Bonasso Desde La Habana Me había preparado para verlo, pero la realidad fue mucho más fuerte. Incluso le llevaba de regalo un ordenador de viaje. Es decir una suerte de cartuchera de cuero argentino, que en su interior tiene espacios predeterminados para papeles, tarjetas, pasaje, pasaporte, anotaciones varias, todo lo que necesita un viajero. Sé muy bien que...
1
1526
by: gandalf | last post by:
CON LA PASION DE SIEMPRE HABLO DE CHAVEZ, DE LA MEDICINA CUBANA... Y DE SU PROPIA MUERTE Relato de la nueva gran batalla de Fidel El líder cubano mostró cómo evoluciona su recuperación en el encuentro con el diputado argentino. También elogió a Hugo Chávez por su lucha para ingresar al Consejo Permanente de la ONU y por aliarse a sectores medios para "hacer los cambios democráticamente" y mostró su preocupación por terminar de editar sus...
1
1628
by: Sebastien | last post by:
Bonjour, Je tient d'abort a m'excuser de poster cette demande ici, mais je ne vois pas tres bien ou fair cette demande, Je développe un logiciel de génération de code (Génération de Code VB et PHP), il est depuis longtemps très aboutie (utiliser en production sur de nombreux developpement interne y compris pour des grand compte, (Télé2,Osram,EstVideo, ...) et propose de nombreuse fonctionnalite inedite a ma connessance dans d'autre...
0
8674
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
8603
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
9157
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...
0
8861
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6518
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
4369
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
4619
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3046
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
3
2001
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.