473,654 Members | 3,040 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

NULL: Is it guaranteed to evaluate 'not true'

Is NULL guaranteed to evaluate 'not true', e.g. is it completely safe and
portable to write:

char *pFoo = malloc(1024);
if (pFoo)
{
/* use pFoo
*/
free(pFoo);
}

Or must I check against NULL explicitly as in:

if (pFoo != NULL) ...

Thanks.

--
- Mark ->
--
Nov 13 '05 #1
19 2527
Mark A. Odell <no****@embedde dfw.com> scribbled the following:
Is NULL guaranteed to evaluate 'not true', e.g. is it completely safe and
portable to write: char *pFoo = malloc(1024);
if (pFoo)
{
/* use pFoo
*/
free(pFoo);
}


AFAIK it's indeed guaranteed to evaluate as "not true". Some C expert
will probably offer a more qualified opinion here.

--
/-- Joona Palaste (pa*****@cc.hel sinki.fi) ---------------------------\
| Kingpriest of "The Flying Lemon Tree" G++ FR FW+ M- #108 D+ ADA N+++|
| http://www.helsinki.fi/~palaste W++ B OP+ |
\----------------------------------------- Finland rules! ------------/
"This isn't right. This isn't even wrong."
- Wolfgang Pauli
Nov 13 '05 #2

"Mark A. Odell" <no****@embedde dfw.com> wrote in message
news:Xn******** *************** *********@130.1 33.1.4...
Is NULL guaranteed to evaluate 'not true',
Yes.
e.g. is it completely safe and
portable to write:

char *pFoo = malloc(1024);
Portable, but not safe, since you didn't check
if malloc() succeeded or failed. If it failed,
then a dereference of 'pFoo' will give undefined
behavior.
if (pFoo)
This will be true if 'pFoo' is not == NULL.
{
/* use pFoo
*/
free(pFoo);
}

Or must I check against NULL explicitly as in:

if (pFoo != NULL) ...


No, you don't have to, but many coders prefer to
explicitly compare against NULL in the interest
of clarity.

-Mike
Nov 13 '05 #3
"Mike Wahler" <mk******@mkwah ler.net> wrote in
news:vb******** *********@newsr ead3.news.pas.e arthlink.net:
NULL: Is it guaranteed to evaluate 'not true'
Yes.
e.g. is it completely safe and
portable to write:

char *pFoo = malloc(1024);


Portable, but not safe, since you didn't check
if malloc() succeeded or failed.


I didn't? What's the following if (pFoo) for then? I did not dereference
pFoo until after the check if (pFoo).
If it failed,
then a dereference of 'pFoo' will give undefined
behavior.
if (pFoo)


This will be true if 'pFoo' is not == NULL.
{
/* use pFoo
*/
free(pFoo);
}

Or must I check against NULL explicitly as in:

if (pFoo != NULL) ...


No, you don't have to, but many coders prefer to
explicitly compare against NULL in the interest
of clarity.


I am certainly not one of them. I prefer C's "boolean" comparisons to
explicit values. Thanks for the reply.

--
- Mark ->
--
Nov 13 '05 #4
"Mark A. Odell" <no****@embedde dfw.com> wrote in message
news:Xn******** *************** *********@130.1 33.1.4...
"Mike Wahler" <mk******@mkwah ler.net> wrote in
news:vb******** *********@newsr ead3.news.pas.e arthlink.net:
NULL: Is it guaranteed to evaluate 'not true'
Yes.
e.g. is it completely safe and
portable to write:

char *pFoo = malloc(1024);


Portable, but not safe, since you didn't check
if malloc() succeeded or failed.


I didn't? What's the following if (pFoo) for then? I did not dereference
pFoo until after the check if (pFoo).


I'm still asleep it seems. :-)
If it failed,
then a dereference of 'pFoo' will give undefined
behavior.
if (pFoo)


This will be true if 'pFoo' is not == NULL.
{
/* use pFoo
*/
free(pFoo);
}

Or must I check against NULL explicitly as in:

if (pFoo != NULL) ...


No, you don't have to, but many coders prefer to
explicitly compare against NULL in the interest
of clarity.


I am certainly not one of them.


Nor am I, except when constrained by coding standards
that require it.

<I prefer C's "boolean" comparisons to explicit values.
As do I.
Thanks for the reply.


Thanks for the wake-up. :-)

-Mike
Nov 13 '05 #5
On 25 Sep 2003 17:59:15 GMT, "Mark A. Odell" <no****@embedde dfw.com>
wrote:
Is NULL guaranteed to evaluate 'not true', e.g. is it completely safe and
portable to write:

char *pFoo = malloc(1024);
if (pFoo)
{
/* use pFoo
*/
free(pFoo);
}


Correct and entirely safe.

if() expects an integer expression, which conventionally would be
the result yielded by a relational operator such as !=. This
result will either by zero (false) or non-zero (true).

If if() is supplied with a pointer expression this causes an
implicit pointer-to-integer conversion. In this case a
non-NULL pointer is converted to a non-zero integer. The NULL
pointer is converted to zero.

Nick.

Nov 13 '05 #6

On Thu, 25 Sep 2003, Nick Austin wrote:

On 25 Sep 2003 17:59:15 GMT, "Mark A. Odell" wrote:

Is NULL guaranteed to evaluate 'not true', e.g. is it completely safe and
portable to write:

char *pFoo = malloc(1024);
if (pFoo)
Correct and entirely safe.

if() expects an integer expression,


Not true. 'if' expects to be controlled by an expression of
*scalar* type (basically, anything except an aggregate).
which conventionally would be
the result yielded by a relational operator such as !=. This
result will either by zero (false) or non-zero (true).
Sort of. 'if' compares its controlling expression to 0. If
it's not equal to 0, the body of the 'if' is executed. Otherwise,
the body of the 'if' is *not* executed. That's all.

For example,

if (foo)

is exactly equivalent to

if ((foo) != 0)

[you see now why aggregate types are not permitted in 'if'
conditions]. So, specifically,

if (pFoo)
if ((pFoo) != 0)

are equivalent expressions. And since 0 is in a pointer
context here, it's equivalent to a null pointer of type 'char *';
that is,

if (pFoo)
if ((pFoo) != NULL)
if ((pFoo) != (char*)0)

are also all equivalent. And of course they all do what you'd
expect.

If if() is supplied with a pointer expression this causes an
implicit pointer-to-integer conversion.


Nonsense. There is no "implicit pointer-to-integer conversion."
Ever. Under any circumstances. The language specifically
forbids it. The only implicit conversions are from pointers
to other pointer types, or from arrays to pointers, or between
different arithmetic types. That's it. (Unless I missed one.)

-Arthur
Nov 13 '05 #7

"Nick Austin" <ni**********@n ildram.co.uk> wrote in message
news:m7******** *************** *********@4ax.c om...
if() expects an integer expression, which conventionally would be
the result yielded by a relational operator such as !=. This
result will either by zero (false) or non-zero (true).

If if() is supplied with a pointer expression this causes an
implicit pointer-to-integer conversion.


This is news to me. Chapter and verse?

-Mike
Nov 13 '05 #8
"Mike Wahler" <mk******@mkwah ler.net> writes:
"Nick Austin" <ni**********@n ildram.co.uk> wrote in message
news:m7******** *************** *********@4ax.c om...
if() expects an integer expression, which conventionally would be
the result yielded by a relational operator such as !=. This
result will either by zero (false) or non-zero (true).

If if() is supplied with a pointer expression this causes an
implicit pointer-to-integer conversion.


This is news to me. Chapter and verse?


(To me too...)

Actually, the "implied conversion" would be integer-to-pointer,
since (according to the standard's definition), the scalar
expression will be compared with 0, requiring 0 to be converted
to NULL first.

(Naturally, by the as-if clause, no actual conversion is likely
in practice...)

-Micah
Nov 13 '05 #9
"Mark A. Odell" <no****@embedde dfw.com> wrote in message news:<Xn******* *************** **********@130. 133.1.4>...
Is NULL guaranteed to evaluate 'not true',
Yes. The 'truth' of an arbitrary expressions X is determined by whether
"the expression compares unequal to 0." i.e. (X != 0).
e.g. is it completely safe and
portable to write:

char *pFoo = malloc(1024);
if (pFoo)
{
/* use pFoo
*/
free(pFoo);
}
Yes.

Or must I check against NULL explicitly as in:

if (pFoo != NULL) ...


No.

--
Peter
Nov 13 '05 #10

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

Similar topics

6
341
by: William Payne | last post by:
Consider the following code: struct foo { char* bar; }; // fooptr is of type foo* if(fooptr != NULL && fooptr->bar != NULL) {
13
3074
by: Don Vaillancourt | last post by:
What's going on with Javascript. At the beginning there was the "undefined" value which represented an object which really didn't exist then came the null keyword. But yesterday I stumbled across "null" string. I know that I will get an "undefined" when I try to retrieve something from the DOM which doesn't exist. I have used null myself to initialize or reset variables. But in which
6
4321
by: TJS | last post by:
how to check for null attribute in form input field using IE this does not work in IE var curr_id = tablecells.getAttribute('name'); if (curr_id != null){ .... }
10
1548
by: DevarajA | last post by:
I've read that 0 is the 'null pointer constant', and assigning it to a pointer makes it a 'null pointer'. Is that true? And is the opposite true? (assigning a null pointer to an int sets the int to 0)? Or should I replace all my if(pointer) with if(pointer!=NULL)? Another question: how does NULL evaluate? -- Devaraja (Xdevaraja87^gmail^c0mX) Linux Registerd User #338167 http://counter.li.org
102
5971
by: junky_fellow | last post by:
Can 0x0 be a valid virtual address in the address space of an application ? If it is valid, then the location pointed by a NULL pointer is also valid and application should not receive "SIGSEGV" ( i am talking of unix machine ) while trying to read that location. Then how can i distinguish between a NULL pointer and an invalid location ? Is this essential that NULL pointer should not point to any of the location in the virtual address...
13
8679
by: Federico Balbi | last post by:
Hi, I was wondering if PGSQL has a function similar to binary_checksum() of MS SQL Server 2000. It is pretty handy when it comes to compare rows of data instead of having to write long boolean expressions. binary_checksum() takes a list of fields and it returns an integer value which sumarize the row content. Thanks, Fed
5
1739
by: corepaul | last post by:
I am using Acess 2000 and Windows 2000. I have a form with a text box txLName. tStrGlobal As String is dimensioned globally. The first time I enter the text box, the Enter event with the code If txLName.Value = Null Then tStrGlobal = "" Else tStrGlobal = txLName.Value ' error occurs in this line End If
9
4485
by: arundelo | last post by:
Is there a way to tell whether accessing a variable will result in an "Undefined variable" E_NOTICE? isset() almost does this, but it also returns false if a variable is set to null: $SetNonNull = 0; $SetNull = null; var_dump(isset($SetNonNull)); // bool(true) $Junk = $SetNonNull; // No error, as predicted by isset(). var_dump(isset($NotSet)); // bool(false)
17
4433
by: copx | last post by:
I don't know what to think of the following.. (from the dietlibc FAQ) Q: I see lots of uninitialized variables, like "static int foo;". What gives? A: "static" global variables are initialized to 0. ANSI C guarantees that. Technically speaking, static variables go into the .bss ELF segment, while "static int foo=0" goes into .data. Because .bss is zero filled by the OS, it does not need to be in the actual binary. So it is in fact...
0
8375
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
8815
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
8482
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
8593
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...
0
7306
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 launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5622
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
4149
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
2714
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
1593
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.