473,396 Members | 1,975 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

Is this correct according to C coding standards?

Dear all,
In one of our projects in a document about C coding standard it is
stated as
"Always check a pointer is NULL before calling free. Always set a
free'd pointer to NULL to try to protect it from being used again
later and causing memory leaks."

My doubt is,"Is this standard practice every where?"Also is it valid
to free a pointer after the value is set to NULL?Because AFAIK,NULL
means it points to nowhere!

Another doubt in the similar manner:I am not able to understand the
behaviour of this code:

char *ptr;
if ((ptr = (char *)malloc(0)) ==
NULL)
puts("Got a null pointer");
else
puts("Got a valid pointer");
This piece of code gives "Got a valid pointer".How come when I specify
a size of zero,memory is allocated and ptr becomes a valid pointer?
I am not able to get the proper reason ,can anyone enlighten me the
reason behind this?

Looking farward for all your replys and advanced thanks for the same,
Regards,
s.subbarayan
Nov 14 '05 #1
8 1792
s.subbarayan wrote:
Dear all,
In one of our projects in a document about C coding standard it is
stated as
"Always check a pointer is NULL before calling free. Always set a

Redundant. free on null pointer is well defined by standard(no action
occurs).
free'd pointer to NULL to try to protect it from being used again
later and causing memory leaks."

Setting a pointer to null after free is a good idea as it eliminates the
possibilty of free memory read.
My doubt is,"Is this standard practice every where?"Also is it valid
to free a pointer after the value is set to NULL?Because AFAIK,NULL
means it points to nowhere!

Another doubt in the similar manner:I am not able to understand the
behaviour of this code:

char *ptr;
if ((ptr = (char *)malloc(0)) ==
NULL)
puts("Got a null pointer");
else
puts("Got a valid pointer");
This piece of code gives "Got a valid pointer".How come when I specify
a size of zero,memory is allocated and ptr becomes a valid pointer?
I am not able to get the proper reason ,can anyone enlighten me the
reason behind this?

Already in FAQ

http://www.eskimo.com/~scs/C-faq/q11.26.html

Krishanu

Nov 14 '05 #2
s_**********@rediffmail.com (s.subbarayan) writes:
In one of our projects in a document about C coding standard it is
stated as
"Always check a pointer is NULL before calling free. Always set a
free'd pointer to NULL to try to protect it from being used again
later and causing memory leaks."

My doubt is,"Is this standard practice every where?"Also is it valid
to free a pointer after the value is set to NULL?Because AFAIK,NULL
means it points to nowhere!

Another doubt in the similar manner:I am not able to understand the
behaviour of this code:

char *ptr;
if ((ptr = (char *)malloc(0)) ==
NULL)
puts("Got a null pointer");
else
puts("Got a valid pointer");
The cast is superfluous; you can change
ptr = (char *)malloc(0)
to
ptr = malloc(0)
malloc() returns a pointer to void, which is implicitly converted to
whatever pointer type you assign it to. But that's a minor point.
This piece of code gives "Got a valid pointer".How come when I specify
a size of zero,memory is allocated and ptr becomes a valid pointer?
I am not able to get the proper reason ,can anyone enlighten me the
reason behind this?


Here's what the standard says:

For malloc(), calloc(), and realloc():

If the space cannot be allocated, a null pointer is returned. If
the size of the space requested is zero, the behavior is
implementation defined: either a null pointer is returned, or the
behavior is as if the size were some nonzero value, except that
the returned pointer shall not be used to access an object.

For free()

The free function causes the space pointed to by ptr to be
deallocated, that is, made available for further allocation. If
ptr is a null pointer, no action occurs.

There's no need to check whether a pointer is null before calling
free; free(NULL) is perfectly valid, and does nothing. (There may be
some very old pre-ANSI implementations that misbehave on free(NULL).
There's usually no need for coding standards to cater to such
implementations.)

Setting a pointer to NULL after freeing it:
free(ptr);
ptr = NULL;
provides some slight protection, but it's not absolute. For example:
ptr = malloc(whatever);
another_ptr = ptr;
free(ptr);
ptr = NULL;
Here I've set ptr to NULL, but another_ptr still contains a copy of
the (now invalid) pointer value. I won't argue that you *shouldn't*
set the pointer to NULL, but don't expect it to catch all your errors;
there's no substitute for careful programming that avoids referring to
free()d pointers.

As for malloc(0), it can return either a null pointer or a valid
pointer (though one that's not particularly useful). If your program
might call malloc() with an argument of 0, you'll need to deal with
both possibilities.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Nov 14 '05 #3
On 8 Mar 2005 02:18:13 -0800, s.subbarayan wrote:
Dear all,
In one of our projects in a document about C coding standard it is
stated as
"Always check a pointer is NULL before calling free. Always set a
free'd pointer to NULL to try to protect it from being used again
later and causing memory leaks."
<snip>

The purpose of free() is to deallocate memory that was allocated by any of
the allocation functions. If you do this:

char *p = malloc(n);
if (p != NULL)
{
p = NULL;
}
free(p);

you have just leaked memory. Your pointer needs to be pointing to what you
want to free when you free it. If your pointer is null when passed to free,
free will do nothing. After you have free'd your memory (properly), it is
considered good practice to set the pointer to NULL for future error
checking, just to make sure you don't use an invalid pointer.
Another doubt in the similar manner:I am not able to understand the
behaviour of this code:

char *ptr;
if ((ptr = (char *)malloc(0)) ==
NULL)
puts("Got a null pointer");
else
puts("Got a valid pointer");

<snip>

In the case of:

char *p = malloc(0);

malloc has two choices: either it can return a non-null pointer which you
can not dereference, or it can return NULL. It is up to malloc to decide
which to return.
Nov 14 '05 #4
s.subbarayan <s_**********@rediffmail.com> wrote:
In one of our projects in a document about C coding standard it is
stated as
"Always check a pointer is NULL before calling free. Always set a
free'd pointer to NULL to try to protect it from being used again
later and causing memory leaks." My doubt is,"Is this standard practice every where?"Also is it valid
to free a pointer after the value is set to NULL?Because AFAIK,NULL
means it points to nowhere!
I don't know if this standard practice everywhere since I don't know
everywhere;-). But since calling free() on a NULL pointer is legal
(it is a no-op) I don't really see what it's meant to be good for.
On the other hand, setting a free()ed pointer to NULL is a quite
common practise that can help to find bugs where it is attempted to
use already free()ed memory, i.e. memory you don't own anymore - if
you set a pointer to NULL after free()ing what it was pointing to
the program will crash immediately when you try to dereference the
pointer, giving a clear indication that something is badly broken.
Of course, that's not a silver bullet since other pointers may still
exist also pointing to the free()ed memory region which you won't
find that way...
Another doubt in the similar manner:I am not able to understand the
behaviour of this code: char *ptr;
if ((ptr = (char *)malloc(0)) ==
NULL)
puts("Got a null pointer");
else
puts("Got a valid pointer"); This piece of code gives "Got a valid pointer".How come when I specify
a size of zero,memory is allocated and ptr becomes a valid pointer?
There's no memory allocated in that case. You only get a pointer but
with no memory attached to it you could really use. The pointer can
only be used as an argument in calls of free() or realloc().
I am not able to get the proper reason ,can anyone enlighten me the
reason behind this?


I guess the rationale behind this is symmetry with realloc(). When you
call realloc() with a valid pointer but a zero size it frees the memory
the pointer was pointing to - but in this case realloc() can't return a
NULL pointer since that would make the return value indistinguishable
from a failure. So realloc() must free() the memory but return the
pointer it was called with also in this case. And malloc() obviously
mimics this behavior to make things as similar as possible, allowing
you to use one function in place of the other in many places, which
can often make things quit a bit simpler.

Regards, Jens
--
\ Jens Thoms Toerring ___ Je***********@physik.fu-berlin.de
\__________________________ http://www.toerring.de
Nov 14 '05 #5
On Tue, 08 Mar 2005 02:18:13 -0800, s.subbarayan wrote:
Dear all,
In one of our projects in a document about C coding standard it is
stated as
"Always check a pointer is NULL before calling free.
This used to be a sensible thing to do. However since C was first
standardised in 1989 free() has been specified to do nothing when passed a
null pointer. 15+ years on it is reasonable to assume that all compilers
you are likely to meet will implement this behaviour. Only worry about
this if you know you will have to use a VERY old compiler.
Always set a
free'd pointer to NULL to try to protect it from being used again
later and causing memory leaks."
This won't protect against memory leaks i.e. failing to free unused memory
in the first place. It also doesn't provide the other protection stated
because you would have to set ALL pointers into that block of memory to
null not just the one that happens to be being used to pass a value to
free(). Where the null pointer is meaningful (e.g. at a terminal node in
some datastructure) then setting it to null when it no longer points at
anything is vital. When the pointer should simply never be used again
after then free() call then simply make sure you don't use it again. E.g.
if you free() a pointer that is a local automatic function variable then
shortly after return from the function there is no value in setting the
pointer to null.
My doubt is,"Is this standard practice every where?
There are very few if any coding standards that are standard practice
"everywhere".
"Also is it valid to
free a pointer after the value is set to NULL?Because AFAIK,NULL means
it points to nowhere!
As noted above free() is well defined when passed a null pointer, it does
nothing.
Another doubt in the similar manner:I am not able to understand the
behaviour of this code:

char *ptr;
if ((ptr = (char *)malloc(0)) ==
NULL)
puts("Got a null pointer");
else
puts("Got a valid pointer");
This piece of code gives "Got a valid pointer".How come when I specify a
size of zero,memory is allocated and ptr becomes a valid pointer? I am
not able to get the proper reason ,can anyone enlighten me the reason
behind this?


The reason is that the standad says it can. It can also return a null
pointer. Of course malloc() is always at liberty to return a null
pointer, but some implementations will always do so when malloc() is
passed 0.

Lawrence

Nov 14 '05 #6
"s.subbarayan" wrote:

In one of our projects in a document about C coding standard it is
stated as
"Always check a pointer is NULL before calling free. Always set a
free'd pointer to NULL to try to protect it from being used again
later and causing memory leaks."

My doubt is,"Is this standard practice every where?" Also is it
valid to free a pointer after the value is set to NULL? Because
AFAIK,NULL means it points to nowhere!
Above edited to insert blanks at the end of sentences, and make it
readable. The blank shortage is over. There is no reason to
obfuscate your article, especially if one of your objectives is to
get people to read it.

It is valid to pass NULL to free, because the standard specifically
says so. Re-freeing a pointer does not cause a memory leak, it
causes undefined behaviour, and often a crash. Thus the ability to
free(NULL) is convenient.

Another doubt in the similar manner: I am not able to understand the
behaviour of this code:

char *ptr;
if ((ptr = (char *)malloc(0)) == NULL)
puts("Got a null pointer");
else
puts("Got a valid pointer");
Get rid of the cast. All it does is inhibit warnings.

This piece of code gives "Got a valid pointer". How come when I
specify a size of zero, memory is allocated and ptr becomes a
valid pointer? I am not able to get the proper reason, can
anyone enlighten me the reason behind this?


See above on the care and feeding of blanks. Once more, the
pointer is valid because the standard says it must be. It can't be
dereferenced because no valid object can occupy zero bytes. It is
up to the implementor to meet these criteria.

--
"If you want to post a followup via groups.google.com, don't use
the broken "Reply" link at the bottom of the article. Click on
"show options" at the top of the article, then click on the
"Reply" at the bottom of the article headers." - Keith Thompson
Nov 14 '05 #7
CBFalconer wrote:

"s.subbarayan" wrote:
Another doubt in the similar manner: I am not able to understand the
behaviour of this code:

char *ptr;
if ((ptr = (char *)malloc(0)) == NULL)
puts("Got a null pointer");
else
puts("Got a valid pointer");


Get rid of the cast. All it does is inhibit warnings.

This piece of code gives "Got a valid pointer". How come when I
specify a size of zero, memory is allocated and ptr becomes a
valid pointer? I am not able to get the proper reason, can
anyone enlighten me the reason behind this?


See above on the care and feeding of blanks. Once more, the
pointer is valid because the standard says it must be.


The standard also allows malloc to return NULL in that situation.

--
pete
Nov 14 '05 #8
Quentarez <qu*******@cognitiveprocess.com> writes:
On 8 Mar 2005 02:18:13 -0800, s.subbarayan wrote:
Dear all,
In one of our projects in a document about C coding standard it is
stated as
"Always check a pointer is NULL before calling free. Always set a
free'd pointer to NULL to try to protect it from being used again
later and causing memory leaks."

<snip>

The purpose of free() is to deallocate memory that was allocated by any of
the allocation functions. If you do this:

char *p = malloc(n);
if (p != NULL)
{
p = NULL;
}
free(p);

you have just leaked memory.

[snip]

I don't think that's what the OP (or the coding standard he's asking
about) meant. I think it means "Always check *whether* a pointer is
NULL before calling free" (i.e., don't call free(NULL)). It's a bad
rule unless it's intended to accomodate pre-ANSI implementations, but
it doesn't cause memory leaks.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Nov 14 '05 #9

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

Similar topics

3
by: ganesan | last post by:
Hi Guys, Could any one knows the best coding standards styles(with variable declarations for c#) . and if any links or site with the best coding standards for .NET send me those links regards...
4
by: dotNetDave | last post by:
About three weeks ago I released the first .NET coding standards book titled "VSDN Tips & Tricks .NET Coding Standards". Here is what the famous author/ speaker Deborah Kurata says about it: ...
11
by: Konrad Den Ende | last post by:
I have a function returning a string but the problem is that the color of it is blue which suits me well for some pages but not for others. Is it possible to "feel" what the color of the background...
5
by: db2sysc | last post by:
ALl. Is it possible to get MS ACCESS CODING STANDARDS? TIA
144
by: Natt Serrasalmus | last post by:
After years of operating without any coding standards whatsoever, the company that I recently started working for has decided that it might be a good idea to have some. I'm involved in this...
7
by: Ralph Lund | last post by:
Hi. I am starting a new project with C#. I am searching for "good" coding conventions. I know that there are some coding conventions from microsoft, (but they are very extensive and not clear)....
3
by: editormt | last post by:
A recent poll asked if programming standards are used by development organisations... and if they are controlled. None: 20% Yes, but without control: 49% Yes, with control: 31% Participants:...
0
by: pat | last post by:
CodeCheck Coding Standard's Support As a free service to our customers we offer support in developing "rule-files" for automating corporate coding standards. If you have a coding standard that...
9
by: dom.k.black | last post by:
Can anyone recommend a good existing C++ coding standard - parctical, pragmatic and sensible? A company I joined recently are moving from C to C++, they are very much into coding standards. But...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
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,...
0
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...
0
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,...

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.