473,698 Members | 2,153 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 1865
In article <9N************ *************** ***@bt.com>,
Richard Heathfield <rj*@see.sig.in validwrote:
>This looks like a bug with DJGPP.
>It isn't. It's a bug in the program. It dereferences NULL.
It may not be a bug in the compiler, but it's certainly a deficiency
that it does not detect the error.

-- Richard
--
Please remember to mention me / in tapes you leave behind.
Aug 6 '08 #21
Richard Tobin wrote, On 06/08/08 13:09:
In article <9N************ *************** ***@bt.com>,
Richard Heathfield <rj*@see.sig.in validwrote:
>>This looks like a bug with DJGPP.
>It isn't. It's a bug in the program. It dereferences NULL.

It may not be a bug in the compiler, but it's certainly a deficiency
that it does not detect the error.
Or a feature, providing compatibility with old compilers which did not
detect the error. Specifically with programs that are playing about with
the interrupt vector table in DOS!
--
Flash Gordon
Aug 6 '08 #22
In article <k2************ @news.flash-gordon.me.uk>,
Flash Gordon <sp**@flash-gordon.me.ukwro te:
>It may not be a bug in the compiler, but it's certainly a deficiency
that it does not detect the error.
>Or a feature, providing compatibility with old compilers which did not
detect the error. Specifically with programs that are playing about with
the interrupt vector table in DOS!
So it's a backward-compatible deficiency.

-- Richard
--
Please remember to mention me / in tapes you leave behind.
Aug 6 '08 #23
In article <g7**********@p c-news.cogsci.ed. ac.uk>, ri*****@cogsci. ed.ac.uk
(Richard Tobin) wrote:
[...]
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.
[...]
If one needed a pointer of address 0 in such a case, say where an
architecture had a register at 0 and whose null pointer was non-zero, one
subtract 1 from a char* of address 1:

char* addr_0 = (char*) 1 - 1;
Aug 7 '08 #24
bl********@gish puppy.com (blargg) writes:
In article <g7**********@p c-news.cogsci.ed. ac.uk>, ri*****@cogsci. ed.ac.uk
(Richard Tobin) wrote:
>[...]
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.
[...]

If one needed a pointer of address 0 in such a case, say where an
architecture had a register at 0 and whose null pointer was non-zero, one
subtract 1 from a char* of address 1:

char* addr_0 = (char*) 1 - 1;
That's one approach. Another is to use a non-constant expression:

int non_constant_ze ro = 0;
char *addr_0 = (char*)non_cons tant_zero;

(You could even declare non_constant_ze ro as const if you wanted to
confuse your readers.)

--
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 7 '08 #25
Richard Tobin wrote:
In article <k2************ @news.flash-gordon.me.uk>,
Flash Gordon <sp**@flash-gordon.me.ukwro te:
>>It may not be a bug in the compiler, but it's certainly a deficiency
that it does not detect the error.
>>Or a feature, providing compatibility with old compilers which did not
detect the error. Specifically with programs that are playing about
with the interrupt vector table in DOS!

So it's a backward-compatible deficiency.
This discussion is similar to the "putc and EOF" one going on elsewhere.
The fundamental problem is NULL should ideally be an "out-of-band"
value, but because on the vast majority of architectures pointers are
implemented with the semantics of unsigned integers, and "out-of-band"
value is impossible, and hence the compulsion to use a perfectly
defined address (zero) as the internal representation of storing NULL
in a pointer. Zero is a perfectly valid memory address.

If pointers are implemented as being identical signed integers then one
could use the value -1 for NULL. Another option would be to use the
largest representable value for NULL. An address like 4294967295 is not
used as often as address zero.

Aug 7 '08 #26
Keith Thompson wrote, On 07/08/08 04:50:
bl********@gish puppy.com (blargg) writes:
>In article <g7**********@p c-news.cogsci.ed. ac.uk>, ri*****@cogsci. ed.ac.uk
(Richard Tobin) wrote:
>>[...]
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.
[...]
If one needed a pointer of address 0 in such a case, say where an
architecture had a register at 0 and whose null pointer was non-zero, one
subtract 1 from a char* of address 1:

char* addr_0 = (char*) 1 - 1;

That's one approach. Another is to use a non-constant expression:

int non_constant_ze ro = 0;
char *addr_0 = (char*)non_cons tant_zero;

(You could even declare non_constant_ze ro as const if you wanted to
confuse your readers.)
However, I would say the best approach is to read the examples in the
manual for that particular implementation and use whatever method they
use (which might be a non-standard header providing a suitable pointer
constant). After all, you are trying to do something non-portable so
whatever non-portable method the implementation documentation suggests
will not reduce portability.
--
Flash Gordon
Aug 7 '08 #27
Flash Gordon wrote:
) Keith Thompson wrote, On 07/08/08 04:50:
)That's one approach. Another is to use a non-constant expression:
)>
) int non_constant_ze ro = 0;
) char *addr_0 = (char*)non_cons tant_zero;
)>
)(You could even declare non_constant_ze ro as const if you wanted to
)confuse your readers.)
)
) However, I would say the best approach is to read the examples in the
) manual for that particular implementation and use whatever method they
) use (which might be a non-standard header providing a suitable pointer
) constant). After all, you are trying to do something non-portable so
) whatever non-portable method the implementation documentation suggests
) will not reduce portability.

Almost always, there is a header defining all the hardware addresses. This
even makes it a bit more portable should you decide to switch to a platform
with the same registers at different memory locations.

I remember on the atmels there were include files for every single chip.
SaSW, Willem
--
Disclaimer: I am in no way responsible for any of the statements
made in the above text. For all I know I might be
drugged or something..
No I'm not paranoid. You all think I'm paranoid, don't you !
#EOT
Aug 7 '08 #28
Willem wrote, On 07/08/08 09:09:
Flash Gordon wrote:
) Keith Thompson wrote, On 07/08/08 04:50:
)That's one approach. Another is to use a non-constant expression:
)>
) int non_constant_ze ro = 0;
) char *addr_0 = (char*)non_cons tant_zero;
)>
)(You could even declare non_constant_ze ro as const if you wanted to
)confuse your readers.)
)
) However, I would say the best approach is to read the examples in the
) manual for that particular implementation and use whatever method they
) use (which might be a non-standard header providing a suitable pointer
) constant). After all, you are trying to do something non-portable so
) whatever non-portable method the implementation documentation suggests
) will not reduce portability.

Almost always, there is a header defining all the hardware addresses. This
even makes it a bit more portable should you decide to switch to a platform
with the same registers at different memory locations.

I remember on the atmels there were include files for every single chip.
I would assume that the examples in the manuals used those header files,
so that is covered by my suggestion :-)

Actually, I've come across similar things and that is one reason why I
suggested referring to the documentation for the best method to solve a
problem that cannot be solved portably.
--
Flash Gordon
Aug 10 '08 #29

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
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
9026
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
8893
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
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
5860
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
4619
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3045
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
2328
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.