Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C, can an address of a pointer be 0?

Tags:

c

pointers

I'm reading the solution to a problem in the book Cracking the Coding interview (Q 1.2). The objective there is to implement a function void revers(char* str) in C that reverses a null terminating string.

The solution code looks something like this:

void reverse(char *str)
{
   char* end=str;
   char tmp;
   if(str)
   {
       while(*end)
       {
          end++;
       }
       end--;
       //code to reverse
   }
}

Here, str contains an address right? And if(str) will only evaluate to false if str is 0, right?

So what I'm saying is, is there no chance that str will contain the address 0x0000, thus evaluating if(str) to false?

like image 288
GrowinMan Avatar asked Jul 22 '13 08:07

GrowinMan


People also ask

Can a pointer value be 0?

Note: It is still acceptable to assign the value 0 or NULL to a pointer. The nullptr keyword designates a constant rvalue of type decltype(nullptr) . The typedef expression is typedef decltype(nullptr) nullptr_t , of which nullptr_t is a typedef for decltype(nullptr) that is defined in <cstddef> .

Can you set a pointer to 0 in C?

"it is possible to assign an integer 0 to a pointer" Yes for object pointers.

Is 0 a valid memory address?

Memory address 0 is called the null pointer. Your program is never allowed to look at or store anything into memory address 0, so the null pointer is a way of saying "a pointer to nothing".

What is a 0 address in C?

The fact you can address 0 (the so called null pointer) is simply a language implementation. It is not pointing to memory address 0. The C++ implementation uses this syntax instead to define a pointer that is pointing to nothing.


1 Answers

str does indeed contain an address (it's a pointer to char), and if(str) will evaluate to false iff the str is equal to the null pointer.

Note that the null pointer is not required by the standard to refer to address 0; however, the standard mandates that a literal value of 0 when used in a pointer context must be interpreted by the compiler as the address of the null pointer -- whatever that might be.

This means that the test if(p == 0) is guaranteed to always be the same as if(p == NULL). Also, the conditional if(p) is guaranteed to always be the same as if(p != 0).

Conclusion: your code will always detect a null pointer, but that's not technically the same as a pointer that points to address zero (even though in practice you are going to find that it usually is).

like image 134
Jon Avatar answered Sep 24 '22 01:09

Jon