473,566 Members | 2,785 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 #1
28 1838
>#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.
Whatever the implementation does or doesn't do here, it's not a bug
per the C standard. You may argue that it is a quality-of-implementation
issue that the program fails to delete its own source code.
>NULL can have different
representation s but how come the compiler allows de-referencing NULL
without any compile time or run-time errors?
A C compiler is not required to diagnose a de-reference of NULL at
either compile time or run time. Undefined behaviour can include
fetching zero or ignoring write attempts, or it can include fetching
zero or ignoring write attempts except when the boss or customer
is watching during a demonstration, then catching his tie on fire.
>P.S : I am not discussing DJGPP. I just want to know if this behaviour
is OK with C specs?
No matter what happens in this situation, it's OK with the C specs.
No possible behavior is forbidden, even if it violates the laws of
physics.

Aug 4 '08 #2
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?
The behaviour is defined to be undefined. Here is the relevant bit from
n1256.pdf:

6.5.3.2

4 The unary * operator denotes indirection. If the operand points to a
function, the result is a function designator; if it points to an
object, the result is an lvalue designating the object. If the operand
has type ??pointer to type??, the result has type ??type??. If an
invalid value has been assigned to the pointer, the behavior of the
unary * operator is undefined.87)

Part of the indicated footnote (which is not normative):

Among the invalid values for dereferencing a pointer by the unary *
operator are a null pointer, [ ... ]

Since no constraint is violated, the implementation is not obliged to
emit a diagnostic, though one would be useful. But it's hard to do this
in all possible cases.

Aug 4 '08 #3
rahul <ra*********@gm ail.comwrites:
#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?
The behavior is undefined, which means that any behavior is ok as far
as the standard is concerned. If your implementation produced no
diagnostics but made demons fly out of your nose, it might violate the
laws of physics, but it wouldn't violate the standard.

--
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 #4
rahul said:
#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.
It isn't. It's a bug in the program. It dereferences NULL.
NULL can have different
representations but how come the compiler allows de-referencing NULL
without any compile time or run-time errors?
Removing the programmer's ability to parade his stupidity necessarily
entails removing his ability to be clever when necessary.
P.S : I am not discussing DJGPP. I just want to know if this behaviour
is OK with C specs?
Yes. The Standard doesn't mandate what must happen when the programmer does
this particular kind of stupid thing, so any behaviour is acceptable.

--
Richard Heathfield <http://www.cpax.org.uk >
Email: -http://www. +rjh@
Google users: <http://www.cpax.org.uk/prg/writings/googly.php>
"Usenet is a strange place" - dmr 29 July 1999
Aug 4 '08 #5
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?
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.
P.S : I am not discussing DJGPP. I just want to know if this behaviour
is OK with C specs?
Aug 4 '08 #6
rahul <ra*********@gm ail.comwrote:
char *p = NULL;
printf ("%c\n", *p);
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.
It isn't. Dereferencing a null pointer has undefined behaviour. Crashing
is legal; printing a message and then crashing is legal; and so is
printing any random value, as if it were a normal dereference.

Richard
Aug 4 '08 #7
On 4 Aug, 07:24, rahul <rahulsin...@gm ail.comwrote:
#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?
I've even used a compiler that made it a command line option.
You could choose if dereferencing NULL crashed or not.
Why you would want this option is a good question...

--
Nick Keighley
Aug 4 '08 #8
Nick Keighley <ni************ ******@hotmail. comwrites:
On 4 Aug, 07:24, rahul <rahulsin...@gm ail.comwrote:
#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?

I've even used a compiler that made it a command line option.
You could choose if dereferencing NULL crashed or not.
Why you would want this option is a good question...
The most probable reason is compatibility with a previous implementation
for which it was the (perhaps even documented) behaviour?

Yours,

--
Jean-Marc
Aug 4 '08 #9
Nick Keighley wrote:
On 4 Aug, 07:24, rahul <rahulsin...@gm ail.comwrote:
>#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?

P.S : I am not discussing DJGPP. I just want to know if this
behaviour is OK with C specs?

I've even used a compiler that made it a command line option.
You could choose if dereferencing NULL crashed or not.
Why you would want this option is a good question...
To be notified of invalid deferences (as NULL always is) when the
underlying OS/hardware does not catch it?

Aug 4 '08 #10

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

Similar topics

2
3018
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...
0
1722
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...
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...
0
2220
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
4283
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
1473
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...
1
1614
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,...
1
1505
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...
1
1621
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,...
0
7666
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...
0
7888
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. ...
0
8108
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...
1
7644
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...
0
7951
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...
0
6260
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...
1
5484
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...
0
3626
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1201
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.