r/C_Programming • • Aug 30 '24

Question Why do we use Null pointers?

If we want to "Nullify" something why dont we create a pointer in a controlled way that points to value 0?

0 Upvotes

56 comments sorted by

5

u/[deleted] Aug 30 '24

Not sure what you mean, but "sentinel value" is sometimes useful alternative to using NULL pointer:

const struct node END_NODE;

Then, maybe

struct node *node;

....

node = &END_NODE;

...

if(node == &END_NODE) break;

1

u/[deleted] Aug 30 '24

Alright it seems i was confused NULL with integer 0. NULL can be considered a data type instead of integer 0 right?

3

u/[deleted] Aug 30 '24

No, NULL is integer zero, for all intents and purposes.

1

u/Netblock Aug 30 '24

No, but C23's nullptr is; which is about dumping the baggage that the NULL macro has.

19

u/Immediate-Food8050 Aug 30 '24 edited Aug 30 '24

Welcome to the C community, where you are downvoted for a perfectly valid question. To give you a real answer, NULL is actually quite a pain in the ass due to how arbitrary it is according to the standard. The new C23 wants to fix this by introducing the more modern nullptr, behaving very similarly to C++ equivalent (about as similar as you can get with C semantics). nullptr always expands to a null pointer constant and will behave the same regardless of the type of pointer it is assigned to, which is not the case of NULL. NULL is a macro that usually evaluates to (void *)0 BUT NOT ALWAYS!!! That's important to note because apparently some people don't understand the harm in that :) There are plenty of cases it does not evaluate to a null pointer constant as it should. C semantics have quirks that can cause issues with that definition, such as 0 and 0L and 0f all being valid but of different types. I know this answer strays away from the question quite a bit, but I more so wanted to validate your confusion since so many people here would rather smoke their own poles with misinformation for the sole reason of being contrarians that are holier-than-thou.

2

u/[deleted] Aug 30 '24

Yeah i guess everyone here is either senior or black magic magicians by default.

2

u/a4qbfb Aug 30 '24

you are downvoted for a perfectly valid question

The question got downvoted because it makes no sense.

NULL is a macro that evaluates to 0

Most implementations define NULL as (void *)0. This is permitted by the C standard and required by POSIX.

1

u/Immediate-Food8050 Aug 30 '24

Okay, comment fixed. Now address the rest :)

-3

u/a4qbfb Aug 30 '24

The rest of your argument falls apart when NULL is (void *)0 instead of plain 0. And OP's question still doesn't make sense.

1

u/Immediate-Food8050 Aug 30 '24

No it does not. Literally how? So nullptr was just added for no reason? In that case, best start writing your letter to ISO!

-3

u/a4qbfb Aug 30 '24

nullptr was added because NULL is still allowed to be 0. But your entire argument was based on NULL being 0, and now that you've edited it, it (and especially your diatribe about 0L vs 0f) no longer makes sense.

1

u/Immediate-Food8050 Aug 30 '24

So is this just a case of two people disagreeing in the explicitness of NULL within the standard?

-3

u/a4qbfb Aug 30 '24

No, I'm trying to be factual while you're trying to “gotcha” me, but you end up shooting down your own argument by editing it after the fact in an attempt to undercut me.

1

u/Immediate-Food8050 Aug 30 '24

I edited it for the corrections you pointed out! Should I just leave it? What are you trying to accomplish? Because I'm trying to "gotcha" you what would you rather me do to prove otherwise? Cross out previous statements and be explicit that there are edits that are corrections? I don't know reddit etiquette. I don't see what's invalid about my statement. Would an example help? I'm trying to be helpful, not argumentative.

72

u/zzmgck Aug 30 '24

The value where a null pointer is pointing is irrelevant. A null pointer is a pointer that is pointing nowhere--there is no value.

In C, the number 0 was defined as the representation of the null pointer. They could have picked any number, but it would have been painful.

7

u/Cylian91460 Aug 30 '24

Its hardware depends iirc, that means null can be something else then 0, it can be max pointer value for example

5

u/zzmgck Aug 30 '24

True, I should have been more specific and said in C99 the value 0 is used for portability.

One should use NULL when assigning or testing for NULL.

3

u/gizahnl Aug 30 '24

True, I should have been more specific and said in C99 the value 0 is used for portability.

No ;) It's C99 on x86, C99 on some exotic hardware could very well be max value. That's what he said: it's hardware dependent, and the C99 standard has left it "implementation defined"

1

u/zzmgck Aug 30 '24

If we want to get specific, it is more of a POSIX requirement than x86.

0000:0000 is a valid address in the x86 architecture and I recall writing some code to get down to that address.

But your point is well taken that assuming NULL is 0 is not a good one.

2

u/TheSkiGeek Aug 30 '24

Integer value 0 casts to/from (and compares equal to) a “null pointer”. But yes, it’s not guaranteed that a null pointer has the same bit pattern as integer zero on any particular architecture. It’s just some pointer value that’s guaranteed to never be used as a legitimate pointer.

0

u/[deleted] Aug 30 '24

[deleted]

-4

u/[deleted] Aug 30 '24

The adress of the null pointer is 0x0. It's a pointer not an integer but has the value 0.

18

u/TheThiefMaster Aug 30 '24

Not necessarily. You can construct a null pointer from a zero constant, but its actual value could be something else. Known to be the case on CUDA, for example, where the actual value of a null pointer is 0xFFFFFFFF (because in CUDA 0 is a valid non-null address, due to the memory map).

POSIX mandates that null pointers have a 0 bit pattern, so anything Linux (which conforms to POSIX) runs on does follow this.

5

u/carpintero_de_c Aug 30 '24

(GNU/)Linux actually doesn't conform to POSIX completely (see POSIXLY_CORRECT). You would be looking at macOS for that :)

-5

u/Ghyrt3 Aug 30 '24

No, pointer is an integer. It can be cast to get a dereference. But pointers's is ssize_t in C.

37

u/strcspn Aug 30 '24 edited Aug 30 '24

What do you mean by pointing to 0? NULL is the address 0x0

An integer constant expression with the value 0, or such an expression cast to type void *, is called a null pointer constant. If a null pointer constant is converted to a pointer type, the resulting pointer, called a null pointer, is guaranteed to compare unequal to a pointer to any object or function.

3

u/[deleted] Aug 30 '24

Standard-wise, NULL is not necessarily `(void*)0`, but it is in the most implementations. This is where the plan of `nullptr` is coming in C23

5

u/erikkonstas Aug 30 '24

Careful, it is (void *)0, what's not necessarily true is that the bytes representing it are all zeroes.

1

u/strcspn Aug 30 '24

This is a quote from the C99 standard.

4

u/[deleted] Aug 30 '24

Technically, it must be "TRUE" when compared to "0", but its value may not be represented as all zero bits.

See C99 standard, chapter 6.3.2.3.

Also: https://stackoverflow.com/questions/9894013/is-null-always-zero-in-c

13

u/Spiritual-Mechanic-4 Aug 30 '24

null pointers aren't so bad. You know you're in trouble when a pointer is 7.

11

u/[deleted] Aug 30 '24

(void *)0x0 is specifically reserved for pointers that don't point anywhere.

What do you mean by "point to 0"? Point to an integer that's zero (or any other magic value)? It would be possible using magic values, but in many cases, all values need to be represented, and using NULL is easier

5

u/accatyyc Aug 30 '24

What difference would it make?

0

u/[deleted] Aug 30 '24

[deleted]

2

u/accatyyc Aug 30 '24

Maybe - let's say you have a `struct { long, long } *my_struct` - what would you have it point to? You'd need to create "empty" variants of all possibly nullable types, or you might still dereference outside allocated memory

1

u/Swedophone Aug 30 '24

You'd need to create "empty" variants of all possibly nullable types, or you might still dereference outside allocated memory

Yes, but a struct that contains longs would be easy. When the struct contains pointers itself it gets harder, in particular recursive data types such as linked lists, trees etc.

3

u/HashDefTrueFalse Aug 30 '24

Pointer = 0 is not the same as the value pointed to = 0. Or simply:

#define NULL 0 // Common impl

int *ptr;
*ptr = 0; // ptr is a memory address, not 0. Dereferencing gives 0.

int *ptr2 = NULL // ptr is 0. Dereferencing is undefined behaviour.

Not really sure what you mean by "create a pointer in a controlled way that points to value 0". Null pointers (tend to) point to address 0, which we take to mean "nowhere meaningful". We do tend to create them in a "controlled" way.

If you're suggesting having the value zero somewhere in the binary and setting pointers to it's memory address rather than zero, that doesn't quite accomplish the same thing. How are we to know the zero value represents "nothing, null, nil" as apposed to being an actual zero? So we'd note the special memory address, but that's what we already did with address 0 (NULL pointer).

2

u/SmokeMuch7356 Aug 30 '24

NULL represents a well-defined "nowhere"; it's an invalid pointer value that's guaranteed to compare unequal to any pointer to an object or function.

We use it in the following cases:

  • To indicate an error condition; for example, if realloc cannot extend a dynamically allocated buffer it will return NULL;

  • As a sentinel to mark the end of a list of pointers; for example, the last element of the argv vector will be NULL to mark the end of the command line arguments;

  • To indicate that a pointer variable currently isn't pointing to anything; for example, when we free dynamically-allocated memory, we'll often set the pointer variable to NULL;

A pointer is valid when it points to an object during that object's lifetime; once that object is deallocated or goes out of scope, the pointer becomes invalid. Attempting to dereference an invalid pointer leads to undefined behavior. There's no way to know whether a non-NULL pointer is valid or not based on the value alone, so we use NULL to explicitly indicate that a pointer is invalid.

1

u/flatfinger Aug 30 '24

You forgot the most important thing about null pointers: while a system would be allowed to use multiple bit patterns to represent null pointers, every null pointer, no matter how derived, is guaranteed to compare equal to every other. I think it's also important to make clear that null pointers are valid pointers. The Standard doesn't specify the effects of trying to dereference them, but it certainly defines the effects of assignments and equality comparisons involving them. By contrast, after free(p);, the Standard would allow implementations to process equality comparisons involving p in any manner whatsoever unless p was null (in which case the behavior of free(0); would be defined as a no-op).

1

u/binarycow Aug 30 '24

why dont we create a pointer in a controlled way that points to value 0?

That's called NULL

1

u/cateanddogew Aug 30 '24 edited Nov 05 '24

fly cause run snatch office rich combative concerned profit numerous

This post was mass deleted and anonymized with Redact

1

u/Maybe-monad Aug 30 '24

Well, I'm too lazy

1

u/chrisekh Aug 30 '24

Null pointer means invalid. 0 can be valid value but null pointer is clear indication that there is no value and there is somekind proplem.

1

u/DawnOnTheEdge Aug 30 '24 edited Aug 30 '24

I’m not sure I understand what you’re asking Historically, C developed out of B, which didn’t have a type system. It was designed for the DEC PDP-8, and everything was a machine word. A pointer was just a machine word that held a machine address, but you could also use it as an integer, by adding or subtracting from it. The machine was word-addressed, so the same integer instructions worked.

Because it was efficient to detect whether a register was equal to 0, 0 became the special value that represented false in an if statement, or an invalid pointer. It also defined true in a way that bitwise & and | doubled as the logical operations.

Basically everything about pointers in C since then is an attempt to add as many other nice things (portability, safety, performance) as possible without breaking backward compatibility. For example, there are a few old mainframes from sixty years ago where NULL does not have all bits set to zero (but Standard C guarantees that, if you set a pointer of any type = 0, that gets you the proper null pointer).

1

u/polypagan Aug 30 '24

The value zero (of length adequate to represent any address) generally makes a good choice as a pointer to "nothing" on most (but not quite all) hardware. Very low addresses on most machines are unlikely hold C-language data or code.

1

u/Environmental-Ear391 Aug 30 '24

Pointers can be Valid or Null,

Pointers can be tested before use

"if(mypointer) { mypointer->xxx =..."

only when the pointer is valid will the write happen... any arbitrary value will see a memory write to an arbitrary memory location...

do you want "memory protection" features of your OS to kill your app?

1

u/GOKOP Aug 30 '24

why dont we create a pointer in a controlled way that points to value 0?

That's... what a null pointer is

2

u/shoolocomous Aug 30 '24

Well, to clarify a null pointer holds address 0, which doesn't point to anything.

A pointer can point to value 0 (the value of the pointer itself being non-null)

2

u/GOKOP Aug 30 '24

Ohhh, they meant a pointer that points to the value 0, not the address 0. (well I guess that's what they literally said, so my bad) Ok then, I see. The answer for OP: Pointers have types which inform you what they point to, not everything has a 0 value, and also 0 can be a legitimate value that someone is trying to use

1

u/nekokattt Aug 30 '24

is there anything saying the value at 0x0 has to itself be 0x0?

1

u/GOKOP Aug 30 '24

I've already clarified in another reply that I misunderstood them as talking about the pointer itself having value 0 (i.e. pointing to address 0). That's all on me ofc because in retrospect the question is pretty clear

1

u/Key_Opposite3235 Aug 30 '24

That is... what we do.

0

u/citit Aug 30 '24

A pointer is a variable that has the following extra meaning associated with it - ”it points to an address”. 0 address is not a valid address. All systems have a well defined memory map where addresses like 0x2000bacd or 0x3000ffff would be valid, but 0 wouldn't be valid. Combine this with the way C initializez global and static variables (pointer is a variable too) to 0 and you get the following extra distinction you can make about a pointer: it's initialized (nonzero) or it's not initialized (zero). You can't do that to a plain variable unless you assign some more meaning to them. You can't tell if uint8_t brightness is initialized or not from its value alone for example.

1

u/mcsuper5 Aug 30 '24

0 is a perfectly valid address. The C library treats it as though it is not. I don't believe the address is writeable on the intel architecture, but most C libraries use it as a flag. Is there a way to read the contents from C, or do you need an assembly routine for that?

0

u/[deleted] Aug 30 '24

[deleted]

2

u/haditwithyoupeople Aug 30 '24

A NULL pointer points to a memory address of 0. That's not the same as pointing to a memory address that has the value 0 stored at that memory address. See the example from u/HashDefTrueFalse above.