RE: freeing NULL pointer

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Hi Ranjith,

I think your questions are somewhat off-topic for this forum.  None of your questions are GCC specific questions.  They are general C / C++ questions which I would expect from someone learning C and/or C++.

I do not say this to chastise.  Rather, you may get better answers faster from a more appropriate C or C++ specific forum which focuses on learning C or C++.

> What happens when we free/delete a NULL pointer?

free() is a library function in the Standard C Library.

This code...

int* p = NULL;
free(p);

...will probably cause problems.  The free() function requires an allocation from malloc(), calloc(), realloc(), or reallocf().  (Or whatever other variants are provided on your platform.)

As I understand how free() works, passing in a NULL pointer is undefined behavior.  Some heap implementations will handle NULL by ignoring it, other heap implementations may crash immediately, and yet other heap implementations may become corrupt but not crash immediately and cause hard to diagnose and seemingly unrelated problems later on.

Instead, use this...

int* p = NULL;
if (p) free(p);

Whereas delete is part of the C++ language.  This code...

int* p = NULL;
delete p;

...or...

int* p = NULL;
delete[] p;

...has well-defined behavior, and is okay to use and does not need to have a if-NULL guard.  And in my opinion, *SHOULD NOT* have an if-NULL guard as such is superfluous and is additional code to maintain, and just "isn't C++" to have an if-NULL guard.

> I read manual pages. No information about it.

For delete, you should read the ISO 14882 section 5.3.5 Delete and 12.4p12 Destructors (calling delete on a NULL pointer has no effect).

> Where can I found how fee() function works? I want to see source code. any links please.

The free() function is not provided by GCC.  What is your platform?

If your platform using GNU C Library, you can look here <http://www.gnu.org/software/libc/>.

> On which macines GCC or any compiler will do 'logical shift' instead of 'arithmetic shift'??

On all of them, when shifting an unsigned integer type.

On all 2's complement machines, when shifting a signed integer type.  (Not sure what happens on 1's complement machines.)

Logical shift is also known as unsigned shift.

Arithmetic shift is also known as signed shift.

Sincerely,
--Eljay


[Index of Archives]     [Linux C Programming]     [Linux Kernel]     [eCos]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [The DWARVES Debugging Tools]     [Yosemite Campsites]     [Yosemite News]     [Linux GCC]

  Powered by Linux