473,396 Members | 1,843 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.

Memory question


Hi All,

As per the standard what is the result of passing NULL to both malloc and free?

Regards,
Mohan.

[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

[ comp.std.c++ is moderated. To submit articles, try just posting with ]
[ your news-reader. If that fails, use mailto:st*****@ncar.ucar.edu ]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://www.jamesd.demon.co.uk/csc/faq.html ]

Nov 14 '05 #1
32 2626
On Fri, 6 Feb 2004 20:33:12 +0000 (UTC), mo************@msn.com
(Mohanasundaram) wrote:

Hi All,

As per the standard what is the result of passing NULL to both malloc and free?
Wow, do you think you've cross-posted to enough groups to guarantee a
good sampling of responses to select from?

I'll reply to just the clc post (thanks, Agent, for giving me the
conscious option)

Passing 0 to free() is a no-op.

Passing it to malloc will return a pointer to a zero-length block of
memory with which you may do absolutely nothing (and don't forget to
free it).
-leor

Regards,
Mohan.

[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

[ comp.std.c++ is moderated. To submit articles, try just posting with ]
[ your news-reader. If that fails, use mailto:st*****@ncar.ucar.edu ]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://www.jamesd.demon.co.uk/csc/faq.html ]


Leor Zolman
BD Software
le**@bdsoft.com
www.bdsoft.com -- On-Site Training in C/C++, Java, Perl & Unix
C++ users: Download BD Software's free STL Error Message
Decryptor at www.bdsoft.com/tools/stlfilt.html
Nov 14 '05 #2
Leor Zolman wrote:
On Fri, 6 Feb 2004 20:33:12 +0000 (UTC), mo************@msn.com
(Mohanasundaram) wrote:

Hi All,

As per the standard what is the result of passing NULL to both malloc
and free?

<snip>
Passing 0 to free() is a no-op.

Passing it to malloc will return a pointer to a zero-length block of
memory with which you may do absolutely nothing (and don't forget to
free it).


It might, instead, legitimately return NULL.

Note that some implementations don't handle malloc(0) well. At least one
implementation of my acquaintance crashes when you try to malloc(0).
Consequently, *even though* the Standard endorses malloc(0), some wise
programmers like to check that their malloc request is not for 0 bytes (if
there is a risk of this) before actually calling malloc.

--
Richard Heathfield : bi****@eton.powernet.co.uk
"Usenet is a strange place." - Dennis M Ritchie, 29 July 1999.
C FAQ: http://www.eskimo.com/~scs/C-faq/top.html
K&R answers, C books, etc: http://users.powernet.co.uk/eton
Nov 14 '05 #3
"Leor Zolman" <le**@bdsoft.com> wrote in message
news:8b********************************@4ax.com...
On Fri, 6 Feb 2004 20:33:12 +0000 (UTC), mo************@msn.com
(Mohanasundaram) wrote:

Hi All,

As per the standard what is the result of passing NULL to both
malloc and free?
Passing 0 to free() is a no-op.

Passing it to malloc will return a pointer to a zero-length block of
memory with which you may do absolutely nothing (and don't forget to
free it).


The OP asked about passing NULL to malloc, not 0. malloc(NULL) may or may
not be a compilation error. In case it isn't, it behaves as you described.

Peter
Nov 14 '05 #4
On Fri, 6 Feb 2004 21:27:57 +0000 (UTC), Richard Heathfield
<do******@address.co.uk.invalid> wrote:
Leor Zolman wrote:
On Fri, 6 Feb 2004 20:33:12 +0000 (UTC), mo************@msn.com
(Mohanasundaram) wrote:

Hi All,

As per the standard what is the result of passing NULL to both malloc
and free?

<snip>

Passing 0 to free() is a no-op.

Passing it to malloc will return a pointer to a zero-length block of
memory with which you may do absolutely nothing (and don't forget to
free it).


It might, instead, legitimately return NULL.

Thanks. I'm still learning how to read the Standard... in this case I
looked at the description for malloc without realizing there was more
"general" info about the allocation function on the previous page that
made this point.
-leor

Leor Zolman
BD Software
le**@bdsoft.com
www.bdsoft.com -- On-Site Training in C/C++, Java, Perl & Unix
C++ users: Download BD Software's free STL Error Message
Decryptor at www.bdsoft.com/tools/stlfilt.html
Nov 14 '05 #5
On Fri, 6 Feb 2004 21:37:24 -0000, "Peter Pichler" <pi*****@pobox.sk>
wrote:
"Leor Zolman" <le**@bdsoft.com> wrote in message
news:8b********************************@4ax.com.. .
On Fri, 6 Feb 2004 20:33:12 +0000 (UTC), mo************@msn.com
(Mohanasundaram) wrote:
>
>Hi All,
>
> As per the standard what is the result of passing NULL to both
malloc and free?

Passing 0 to free() is a no-op.

Passing it to malloc will return a pointer to a zero-length block of
memory with which you may do absolutely nothing (and don't forget to
free it).


The OP asked about passing NULL to malloc, not 0. malloc(NULL) may or may
not be a compilation error. In case it isn't, it behaves as you described.


That was a "C++ mentality" issue -- using 0 to avoid the debate over
the implications of using NULL ;-)

I'm now trying to understand how malloc(NULL) would draw a compile
error... something perhaps about NULL being an
"implementation-defined null pointer constant" that refuses to convert
to a size_t? Help...
Thanks,
-leor

Peter


Leor Zolman
BD Software
le**@bdsoft.com
www.bdsoft.com -- On-Site Training in C/C++, Java, Perl & Unix
C++ users: Download BD Software's free STL Error Message
Decryptor at www.bdsoft.com/tools/stlfilt.html
Nov 14 '05 #6
"Leor Zolman" <le**@bdsoft.com> wrote in message
news:nd********************************@4ax.com...

I'm now trying to understand how malloc(NULL) would draw a compile
error... something perhaps about NULL being an
"implementation-defined null pointer constant" that refuses to convert
to a size_t? Help...


NULL may be #defines as (void*)0 in C.
Nov 14 '05 #7
Mohanasundaram wrote:
As per the standard what is the result of passing NULL to both malloc and free?


There are separate standards for C and C++. We tried to
make them agree as much as possible where the facilities
are mainly "C". So I'll reply only from the point of
view of the current C standard (C99+TC1).

malloc() is passed an integer argument, not a pointer.
So I will asume that you meant realloc(). When the
pointer argument in a call to realloc() is null, the
function acts just like a call to malloc() with the same
size argument.

If the argument to free() is a null pointer, no action
is taken.

Some older (non standards compliant) implementations of
these functions will not behave as the standard specifies,
so for maximal portability you might prefer to avoid
relying on that behavior. This is easy to do:
if (p == NULL)
q = malloc(n);
else
q = realloc(p, n);
if (r != NULL)
free(r);

Nov 14 '05 #8
Peter Pichler wrote:

"Leor Zolman" <le**@bdsoft.com> wrote in message
news:8b********************************@4ax.com...
On Fri, 6 Feb 2004 20:33:12 +0000 (UTC), mo************@msn.com
(Mohanasundaram) wrote:

Hi All,

As per the standard what is the result of passing NULL to both

malloc and free?

Passing 0 to free() is a no-op.

Passing it to malloc will return a pointer to a zero-length block of
memory with which you may do absolutely nothing (and don't forget to
free it).


The OP asked about passing NULL to malloc, not 0. malloc(NULL) may or may
not be a compilation error. In case it isn't, it behaves as you described.

May or may not? NULL is 0 or ((void *)0) and because of C89 prototyping
will arrive at malloc as 'size_t 0' graranteed. What 'compilation error'
were you thinking about?

--
Joe Wright http://www.jw-wright.com
"Everything should be made as simple as possible, but not simpler."
--- Albert Einstein ---
Nov 14 '05 #9
On Sat, 07 Feb 2004 02:22:22 GMT, Joe Wright
<jo********@earthlink.net> wrote in comp.lang.c:
Peter Pichler wrote:

"Leor Zolman" <le**@bdsoft.com> wrote in message
news:8b********************************@4ax.com...
On Fri, 6 Feb 2004 20:33:12 +0000 (UTC), mo************@msn.com
(Mohanasundaram) wrote:
>
>Hi All,
>
> As per the standard what is the result of passing NULL to both

malloc and free?

Passing 0 to free() is a no-op.

Passing it to malloc will return a pointer to a zero-length block of
memory with which you may do absolutely nothing (and don't forget to
free it).


The OP asked about passing NULL to malloc, not 0. malloc(NULL) may or may
not be a compilation error. In case it isn't, it behaves as you described.

May or may not? NULL is 0 or ((void *)0) and because of C89 prototyping
will arrive at malloc as 'size_t 0' graranteed. What 'compilation error'
were you thinking about?


There is no automatic conversion from "void *" to size_t. If an
implementation defines NULL as (void *)0, and there is a prototype for
malloc() in scope identifying the type of the argument as size_t, the
compiler must issue a diagnostic for the constraint violation of
attempting to convert a pointer (of any type) to an integer type
without a cast.

--
Jack Klein
Home: http://JK-Technology.Com
FAQs for
comp.lang.c http://www.eskimo.com/~scs/C-faq/top.html
comp.lang.c++ http://www.parashift.com/c++-faq-lite/
alt.comp.lang.learn.c-c++
http://www.contrib.andrew.cmu.edu/~a...FAQ-acllc.html
Nov 14 '05 #10

Mohanasundaram wrote:
Hi All,

As per the standard what is the result of passing NULL to both malloc and free?


The rules in the C++ standard for malloc and free are the same as in C.

The malloc function takes an integer argument representing size, not NULL, which
is a null pointer constant.

Assuming you meant malloc(0), the results depend on the implementation. An
implementation is allowed always to return a null pointer, or to return a unique
pointer if it can (it's possible to run out of address space). It cannot return
a pointer to an existing object. Whatever the return, you are not allowed to
dereference the pointer, because it need not point to allocated memory. (You
asked for 0 bytes, after all.)

I don't find anything in either standard that disallows always returning the
same non-null address for malloc(0), as long as that address is not othewise used.

The short answer is that malloc(0) is allowed, but you can't depend on doing
much with the result. Allowing malloc(0) simplifies some algorithms.

Passing a null pointer to free() is allowed, and has no net effect.

The net result of these rules is that you can always call free (once) with the
result you got from malloc.

--
Steve Clamage, st*************@sun.com
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

[ comp.std.c++ is moderated. To submit articles, try just posting with ]
[ your news-reader. If that fails, use mailto:st*****@ncar.ucar.edu ]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://www.jamesd.demon.co.uk/csc/faq.html ]
Nov 14 '05 #11

Mohanasundaram wrote:

Hi All,

As per the standard what is the result of passing NULL to both malloc and free?


In C, the behavior of malloc(NULL) depends upon your implementation.
1. NULL can be an integer constant expression with a value of 0, in
which case you've done the eqivalent of calling malloc(0). Per 7.20.3p1
of the C standard:

"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."

2. NULL can be an integer constant expression with a value of 0, cast to
void* (this is not permitted in C++). In that case, malloc(NULL) is
equivalent to malloc((void*)0), which in turn is equivalent to
malloc((size_t)(void*)0). The result of (size_t)(void*)0 is
implementation-defined; it can be any valid size_t value. On a great
many implementations, it will be 0, but there are real implementations
where it might not be, and portable code should not count on that.

free(NULL) is much simpler. Per 7.20.3.2p2 of the C standard: "If ptr is
a null pointer, no action occurs.".

The C++ standard incorporates by reference most of the C standard
library's description. The only changes it makes are to specify that
malloc() does not call ::operator new(), and free() does not call
::operator delete().

[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

[ comp.std.c++ is moderated. To submit articles, try just posting with ]
[ your news-reader. If that fails, use mailto:st*****@ncar.ucar.edu ]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://www.jamesd.demon.co.uk/csc/faq.html ]
Nov 14 '05 #12
Joe Wright <jo********@earthlink.net> wrote in message news:<40***********@earthlink.net>...
Peter Pichler wrote:

"Leor Zolman" <le**@bdsoft.com> wrote in message
news:8b********************************@4ax.com...
On Fri, 6 Feb 2004 20:33:12 +0000 (UTC), mo************@msn.com
(Mohanasundaram) wrote:
.... The OP asked about passing NULL to malloc, not 0. malloc(NULL) may or may
not be a compilation error. In case it isn't, it behaves as you described.

May or may not? NULL is 0 or ((void *)0) and because of C89 prototyping
will arrive at malloc as 'size_t 0' graranteed. What 'compilation error'
were you thinking about?

How do you arrive at 'size_t 0'? The conversion is not implicit -
arguments to function calls are converted according to the same rules
as assignment, and pointer->integer type isn't one of the options
allowed by the constraints on assignment.

However, even if the conversion could occur implicitly, there's
nothing in the standard that guarantees that (size_t)(void*)i == i for
any integer, not even case where 'i' is replaced by a literal '0'.
Nov 14 '05 #13

Steve Clamage <St*************@Sun.COM> wrote in message news:<c0**********@news1nwk.SFbay.Sun.COM>...

The net result of these rules is that you can always call free (once) with the
result you got from malloc.

So I take it MSVC 6's crash on:

char* x = new char[0];
delete [] x;

is most definitely non-compliant...?

Dylan
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

[ comp.std.c++ is moderated. To submit articles, try just posting with ]
[ your news-reader. If that fails, use mailto:st*****@ncar.ucar.edu ]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://www.jamesd.demon.co.uk/csc/faq.html ]
Nov 14 '05 #14

In comp.std.c Steve Clamage <St*************@sun.com> wrote:

I don't find anything in either standard that disallows always returning the
same non-null address for malloc(0), as long as that address is not othewise used.


C99 7.20.3:

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.

C90 contained slightly different language that was more easily misread,
but the intent was the same.

-Larry Jones

It's either spectacular, unbelievable success, or crushing, hopeless
defeat! There is no middle ground! -- Calvin
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

[ comp.std.c++ is moderated. To submit articles, try just posting with ]
[ your news-reader. If that fails, use mailto:st*****@ncar.ucar.edu ]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://www.jamesd.demon.co.uk/csc/faq.html ]
Nov 14 '05 #15

On Sun, 8 Feb 2004 15:32:59 +0000 (UTC), la************@ugsplm.com
wrote:

In comp.std.c Steve Clamage <St*************@sun.com> wrote:

I don't find anything in either standard that disallows always returning the
same non-null address for malloc(0), as long as that address is not othewise used.


C99 7.20.3:

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.

C90 contained slightly different language that was more easily misread,
but the intent was the same.


Yes, and as I said, I don't see anything that prohibits always
returning the same non-null address.

Suppose the malloc/free implementation reserves one byte, malloc(0)
always returns the address of that byte, and free() of that address is
a no-op. I don't see any rule violation.
---
Steve Clamage, st*************@sun.com
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

[ comp.std.c++ is moderated. To submit articles, try just posting with ]
[ your news-reader. If that fails, use mailto:st*****@ncar.ucar.edu ]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://www.jamesd.demon.co.uk/csc/faq.html ]
Nov 14 '05 #16

On Sun, 8 Feb 2004 15:32:59 +0000 (UTC), wi******@hotmail.com (Dylan
Nicholson) wrote:

Steve Clamage <St*************@Sun.COM> wrote in message news:<c0**********@news1nwk.SFbay.Sun.COM>...

The net result of these rules is that you can always call free (once) with the
result you got from malloc.

So I take it MSVC 6's crash on:

char* x = new char[0];
delete [] x;

is most definitely non-compliant...?


Bear in mind the following differences:

A new-expression like
new T // T is some type
new T[size}
is a syntactical construct that causes memory to be allocated by the
memory allocation function associated with type T, followed by
contructor invocation(s) for the allocated object(s).

The C++ standard library contiains six different overloads of operator
new, a function that can be called explicitly to allocate raw memory.
You can also write your own overloads, and replace some of the default
versions. The rules are given in the C++ standard section 18.4.1 and
3.7.3. A new-expression invokes some version of operator new, as
explained in section 5.3.4.

C++ also inherits library functions malloc and free from C, which can
be called explicitly to manage raw storage. The C++ standard does not
require that malloc (or free) be used in the implementation of new (or
delete) expressions, or of operator new (or operator delete).

The code you show involves a new-expression and a delete-expression,
not direct calls to malloc or free.

I read section 5.3.4 to say that the expression
new T[0]
is ill-formed, for any type T. The standard requires a strictly
positive value for the constant-expression giving the array size. But
I tried a couple of compilers at full warning levels, and neither
complained about new char[0].

If the code is invalid, the standard imposes no requirements on the
behavior of the program. But it seems to me that an implemention
allowing the expression should also allow deleteing the pointer that
was returned.

Calling the operator new function explicitly is a different story,
however. The expression
operator new(0)
is valid. If the operation succeeds, it must return a unique address
for each call, which can be passed to the corresponding operator
delete().
---
Steve Clamage, st*************@sun.com
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

[ comp.std.c++ is moderated. To submit articles, try just posting with ]
[ your news-reader. If that fails, use mailto:st*****@ncar.ucar.edu ]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://www.jamesd.demon.co.uk/csc/faq.html ]
Nov 14 '05 #17

wi******@hotmail.com (Dylan Nicholson) writes:
Steve Clamage <St*************@Sun.COM> wrote in message
news:<c0**********@news1nwk.SFbay.Sun.COM>...
> The net result of these rules is that you can always call free
> (once) with the result you got from malloc.
>

So I take it MSVC 6's crash on:

char* x = new char[0];
delete [] x;

is most definitely non-compliant...?


I'm posting in comp.std.c. From that point of view, I'm not sure
whether crashing (at run-time?) on a syntax error is non-compliant.
As long as it generates a diagnostic during compilation, it's probably
all right.

As far as C++ is concerned, I don't know whether the delete []
operator follows the same rules as free(). I've redirected followups
to comp.lang.c++.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://www.sdsc.edu/~kst>
Schroedinger does Shakespeare: "To be *and* not to be"
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

[ comp.std.c++ is moderated. To submit articles, try just posting with ]
[ your news-reader. If that fails, use mailto:st*****@ncar.ucar.edu ]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://www.jamesd.demon.co.uk/csc/faq.html ]

Nov 14 '05 #18

James Kuyper <ku****@saicmodis.com> wrote in message
news:<40***************@saicmodis.com>...
2. NULL can be an integer constant expression with a value of 0, cast
to void* (this is not permitted in C++). In that case, malloc(NULL) is
equivalent to malloc((void*)0), which in turn is equivalent to
malloc((size_t)(void*)0). The result of (size_t)(void*)0 is
implementation-defined; it can be any valid size_t value. On a great
many implementations, it will be 0, but there are real implementations
where it might not be, and portable code should not count on that.
However, the conversion of ((void*)0) to an integral type requires an
explicit cast. If this is the definition of NULL, then malloc(NULL)
should not compile.
free(NULL) is much simpler. Per 7.20.3.2p2 of the C standard: "If ptr
is a null pointer, no action occurs.". The C++ standard incorporates by reference most of the C standard
library's description. The only changes it makes are to specify that
malloc() does not call ::operator new(), and free() does not call
::operator delete().


Yes, but the removal of the liberty to define NULL as ((void*)0) means
that in C++, malloc(NULL) is always legal, where as in C, there are
implementations where it may fail.

--
James Kanze GABI Software mailto:ka***@gabi-soft.fr
Conseils en informatique orientée objet/ http://www.gabi-soft.fr
Beratung in objektorientierter Datenverarbeitung
11 rue de Rambouillet, 78460 Chevreuse, France, +33 (0)1 30 23 45 16
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

[ comp.std.c++ is moderated. To submit articles, try just posting with ]
[ your news-reader. If that fails, use mailto:st*****@ncar.ucar.edu ]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://www.jamesd.demon.co.uk/csc/faq.html ]
Nov 14 '05 #19

On Mon, 9 Feb 2004 03:26:12 +0000 (UTC), Stephen Clamage
<St*************@Sun.COM> wrote:
I read section 5.3.4 to say that the expression
new T[0]
is ill-formed, for any type T. The standard requires a strictly
positive value for the constant-expression giving the array size. But
I tried a couple of compilers at full warning levels, and neither
complained about new char[0].


Maybe another read would help. T[0] contains an expression which must
be non-negative. The expression happens but is not required to be
constant. T[0][5] is a form which requires the second expression to
be constant and positive. Does that make sense?

John
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

[ comp.std.c++ is moderated. To submit articles, try just posting with ]
[ your news-reader. If that fails, use mailto:st*****@ncar.ucar.edu ]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://www.jamesd.demon.co.uk/csc/faq.html ]
Nov 14 '05 #20

Stephen Clamage <St*************@Sun.COM> wrote in message news:<r3********************************@4ax.com>. ..
On Sun, 8 Feb 2004 15:32:59 +0000 (UTC), la************@ugsplm.com
wrote:

In comp.std.c Steve Clamage <St*************@sun.com> wrote:

I don't find anything in either standard that disallows always returning the
same non-null address for malloc(0), as long as that address is not othewise used.


C99 7.20.3:

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.

C90 contained slightly different language that was more easily misread,
but the intent was the same.


Yes, and as I said, I don't see anything that prohibits always
returning the same non-null address.

Suppose the malloc/free implementation reserves one byte, malloc(0)
always returns the address of that byte, and free() of that address is
a no-op. I don't see any rule violation.


I read the above section as requiring that if malloc(0) doesn't return
a null pointer, then there be some value of 'n', possibly different
for each call to malloc(0), for which the behavior of malloc(n) would
be identical to the actual behavior of malloc(0). Fow what size n is
the behavior of malloc(n) the same as the behavior you suggest for
malloc(0)?
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

[ comp.std.c++ is moderated. To submit articles, try just posting with ]
[ your news-reader. If that fails, use mailto:st*****@ncar.ucar.edu ]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://www.jamesd.demon.co.uk/csc/faq.html ]
Nov 14 '05 #21

Stephen Clamage wrote:
Yes, and as I said, I don't see anything that prohibits always
returning the same non-null address.


Since Standard C doesn't include 0-sized objects, if there
is a successful malloc(0) in a conforming implementation,
the associated object will occupy at least one byte,
although a s.c. program isn't allowed to access it.
It would be folly for an implementation to return a pointer
to *the same* 0-sized region for multiple concurrent live
allocations, because those allocations can be free()d and
how then would it know when the last free() occurs (unless
it adds the overhead of a reference count, which would have
no other purpose).
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

[ comp.std.c++ is moderated. To submit articles, try just posting with ]
[ your news-reader. If that fails, use mailto:st*****@ncar.ucar.edu ]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://www.jamesd.demon.co.uk/csc/faq.html ]
Nov 14 '05 #22

St*************@Sun.COM (Stephen Clamage) wrote (abridged):
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.

[...]
Suppose the malloc/free implementation reserves one byte, malloc(0)
always returns the address of that byte, and free() of that address is
a no-op. I don't see any rule violation.


That would not be allowed if the size were some nonzero value.

char *a = malloc( 1 );
char *b = malloc( 1 );
assert( a != b || a == NULL );

The assert must succeed. So it must also succeed if we replace the 1's
with 0's.

-- Dave Harris, Nottingham, UK
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

[ comp.std.c++ is moderated. To submit articles, try just posting with ]
[ your news-reader. If that fails, use mailto:st*****@ncar.ucar.edu ]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://www.jamesd.demon.co.uk/csc/faq.html ]
Nov 14 '05 #23

In comp.std.c Stephen Clamage <St*************@sun.com> wrote:

Yes, and as I said, I don't see anything that prohibits always
returning the same non-null address.


It says that malloc(0) behaves like, for example, malloc(1). Do you
think that malloc(1) is allowed to return the same value all the time?

-Larry Jones

They say winning isn't everything, and I've decided
to take their word for it. -- Calvin
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

[ comp.std.c++ is moderated. To submit articles, try just posting with ]
[ your news-reader. If that fails, use mailto:st*****@ncar.ucar.edu ]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://www.jamesd.demon.co.uk/csc/faq.html ]
Nov 14 '05 #24

Stephen Clamage <St*************@Sun.COM> wrote in message
news:<r9********************************@4ax.com>. ..

[...]
I read section 5.3.4 to say that the expression
new T[0]
is ill-formed, for any type T. The standard requires a strictly
positive value for the constant-expression giving the array size.
I'm not sure. I presume you are referring to §5.3.4/6: "Every
_constant-expression_ in a _direct-new-declarator_ shal be an integral
constant expression evaluating to a strictly positive value." The
following sentence reads "The _expression_ in a _direct-new-declarator_
shall have integral type with a non-negative value." The grammar at the
top of §5.3.4 reads:

[...]
direct-new-declarator:
[ expression ]
direct-new-declarator [ constant-expression ]

Because of the hypen, and because the expression is written in italics,
I would interpret "constant-expression" in the first quote to refer to
the gramatical construct in the second production for
direct-new-declarator, and not to be the equivalent of a simple
"constant expression". In "new char[0]", the [0] matches the first
production above, and not the second, so the constraints of "expressin"
in §5.3.4/6 apply: it must have a non-negative value (but 0 is OK).

In this case, §5.3.4/7 applies: "When the value of the expression in a
direct-new-declarator is zero, the allocation function is called to
allocate an array with no elements. The pointer returned by the
new-expression is non-null."
But I tried a couple of compilers at full warning levels, and neither
complained about new char[0]. If the code is invalid, the standard imposes no requirements on the
behavior of the program. But it seems to me that an implemention
allowing the expression should also allow deleteing the pointer that
was returned.


The closest I could find is §5.3.5/2: "[...] In the second alternative
(delete array), the value of the operand of delete shall be the pointer
value which resulted from a previous array new-expression." I can find
nothing which requires that the number of elements be greater than 0, so
I would assume that the delete is legal.

I might add that, unlike the poster you were responding to, when I
tried:

char* x = new char[0] ;
delete [] x ;

with VC++ 6.0, it worked as expected.

--
James Kanze GABI Software mailto:ka***@gabi-soft.fr
Conseils en informatique orientée objet/ http://www.gabi-soft.fr
Beratung in objektorientierter Datenverarbeitung
11 rue de Rambouillet, 78460 Chevreuse, France, +33 (0)1 30 23 45 16
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

[ comp.std.c++ is moderated. To submit articles, try just posting with ]
[ your news-reader. If that fails, use mailto:st*****@ncar.ucar.edu ]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://www.jamesd.demon.co.uk/csc/faq.html ]
Nov 14 '05 #25

ka***@gabi-soft.fr wrote:

James Kuyper <ku****@saicmodis.com> wrote in message
news:<40***************@saicmodis.com>...
2. NULL can be an integer constant expression with a value of 0, cast
to void* (this is not permitted in C++). In that case, malloc(NULL) is
equivalent to malloc((void*)0), which in turn is equivalent to
malloc((size_t)(void*)0). The result of (size_t)(void*)0 is
implementation-defined; it can be any valid size_t value. On a great
many implementations, it will be 0, but there are real implementations
where it might not be, and portable code should not count on that.


However, the conversion of ((void*)0) to an integral type requires an
explicit cast. If this is the definition of NULL, then malloc(NULL)
should not compile.


More precisely, a diagnostic message is required, a fact that I forgot
to mention, in my haste to cover the NULL issue properly. However,
having issued that message, an implementation is free to continue with
translation and even execution of the program.

[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

[ comp.std.c++ is moderated. To submit articles, try just posting with ]
[ your news-reader. If that fails, use mailto:st*****@ncar.ucar.edu ]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://www.jamesd.demon.co.uk/csc/faq.html ]

Nov 14 '05 #26

la************@ugsplm.com wrote:
In comp.std.c Stephen Clamage <St*************@sun.com> wrote:
Yes, and as I said, I don't see anything that prohibits always
returning the same non-null address.

It says that malloc(0) behaves like, for example, malloc(1). Do you
think that malloc(1) is allowed to return the same value all the time?


I take your point, but I think there is a difference between malloc(0) and
malloc(1).

The expression malloc(1) returns a pointer to an object, whereas malloc(0) does
not. That is, there are no zero-sized objects, and you are not allowed to
dereference the result of malloc(0).

So I think the standard has a loophole that allows an implementation like I
suggested in another posting: Reserve one byte. Have malloc(0) return the
address of that byte, and have free() of that address do nothing. The returns
from malloc never point to any object that was not already free'd.

I'm not seriously recommending this approach. I just think that it doesn't
violate any requirement in the standard.

--
Steve Clamage, st*************@sun.com
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

[ comp.std.c++ is moderated. To submit articles, try just posting with ]
[ your news-reader. If that fails, use mailto:st*****@ncar.ucar.edu ]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://www.jamesd.demon.co.uk/csc/faq.html ]

Nov 14 '05 #27

"Douglas A. Gwyn" <DA****@null.net> writes:
Stephen Clamage wrote:
Yes, and as I said, I don't see anything that prohibits always
returning the same non-null address.


Since Standard C doesn't include 0-sized objects, if there
is a successful malloc(0) in a conforming implementation,
the associated object will occupy at least one byte,
although a s.c. program isn't allowed to access it.
It would be folly for an implementation to return a pointer
to *the same* 0-sized region for multiple concurrent live
allocations, because those allocations can be free()d and
how then would it know when the last free() occurs (unless
it adds the overhead of a reference count, which would have
no other purpose).


Why would the implementation _care_ when the last free() occurs?

--
Fergus Henderson <fj*@cs.mu.oz.au> | "I have always known that the pursuit
The University of Melbourne | of excellence is a lethal habit"
WWW: <http://www.cs.mu.oz.au/~fjh> | -- the last words of T. S. Garp.

[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

[ comp.std.c++ is moderated. To submit articles, try just posting with ]
[ your news-reader. If that fails, use mailto:st*****@ncar.ucar.edu ]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://www.jamesd.demon.co.uk/csc/faq.html ]

Nov 14 '05 #28

Steve Clamage wrote:

la************@ugsplm.com wrote:
> In comp.std.c Stephen Clamage <St*************@sun.com> wrote:
>
>>Yes, and as I said, I don't see anything that prohibits always
>>returning the same non-null address.

>
>
> It says that malloc(0) behaves like, for example, malloc(1). Do you
> think that malloc(1) is allowed to return the same value all the time?
>


I take your point, but I think there is a difference between malloc(0) and
malloc(1).

The expression malloc(1) returns a pointer to an object, whereas malloc(0) does
not. That is, there are no zero-sized objects, and you are not allowed to
dereference the result of malloc(0).


The standard specifies that the behavior of malloc(0), when it does not
return a null pointer, must be the same as the behavior of malloc(n) for
some non-zero value of n. That means it does return a pointer to an
object which is NOT zero-sized. It also says that it's illegal to
dereference the pointer to access that object. However, it's still
perfectly legal to use it for equality comparisons, and it must behave
with respect to those comparisons exactly like the result of malloc(n) -
which means it must compare unequal to any other pointer returned by a
malloc(), unless one of the two pointer values being compared has been
passed to free(), in which case all bets are off.

Switching from issues of what the standard does say, to what it should
say: I think there's a fair amount of code out there written to call
malloc(size) for size values where you don't want to bother having
special handling for size==0, but where you do want to assume that each
non-null return value is unique. That doesn't seem to me to be an
unreasonable style of coding, given the current standard, and such code
would be broken if the standard were changed to allow malloc(0) to
always return the same non-null pointer value.

[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

[ comp.std.c++ is moderated. To submit articles, try just posting with ]
[ your news-reader. If that fails, use mailto:st*****@ncar.ucar.edu ]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://www.jamesd.demon.co.uk/csc/faq.html ]

Nov 14 '05 #29

In comp.std.c Steve Clamage <St*************@sun.com> wrote:

The expression malloc(1) returns a pointer to an object, whereas malloc(0) does
not. That is, there are no zero-sized objects, and you are not allowed to
dereference the result of malloc(0).
I don't agree with your conclusion -- malloc(0) most certainly *does*
return a pointer to an object. Said object is not zero sized ("the
behavior is as if the size were some nonzero value"), but you are not
permitted to access it.
So I think the standard has a loophole that allows an implementation like I
suggested in another posting: Reserve one byte. Have malloc(0) return the
address of that byte, and have free() of that address do nothing. The returns
from malloc never point to any object that was not already free'd.


That does not meet the requirement that each allocation yield a pointer
to an object distinct from any other (live) object.

-Larry Jones

It's not denial. I'm just very selective about the reality I accept.
-- Calvin
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

[ comp.std.c++ is moderated. To submit articles, try just posting with ]
[ your news-reader. If that fails, use mailto:st*****@ncar.ucar.edu ]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://www.jamesd.demon.co.uk/csc/faq.html ]
Nov 14 '05 #30

Steve Clamage <St*************@Sun.COM> wrote in message news:<c0**********@news1nwk.SFbay.Sun.COM>...
The expression malloc(1) returns a pointer to an object, whereas malloc(0) does
not. That is, there are no zero-sized objects, and you are not allowed to
dereference the result of malloc(0).
No, malloc(0) either returns NULL or a pointer to an n-byte object,
for some unspecified nonzero n. This object must be disjoint from any
other object. You're not allowed to access the object, but you can
compare its address to addresses of other objects, and you can expect
them to turn out different.
So I think the standard has a loophole that allows an implementation like I
suggested in another posting: Reserve one byte. Have malloc(0) return the
address of that byte, and have free() of that address do nothing. The returns
from malloc never point to any object that was not already free'd.

I'm not seriously recommending this approach. I just think that it doesn't
violate any requirement in the standard.


Except the one that it must be an object of a non-zero size, disjoint
from any other object.
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

[ comp.std.c++ is moderated. To submit articles, try just posting with ]
[ your news-reader. If that fails, use mailto:st*****@ncar.ucar.edu ]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://www.jamesd.demon.co.uk/csc/faq.html ]
Nov 14 '05 #31

In <c0**********@news1nwk.SFbay.Sun.COM> Steve Clamage <St*************@Sun.COM> writes:

So I think the standard has a loophole that allows an implementation like I
suggested in another posting: Reserve one byte. Have malloc(0) return the
address of that byte, and have free() of that address do nothing. The returns
from malloc never point to any object that was not already free'd.

I'm not seriously recommending this approach. I just think that it doesn't
violate any requirement in the standard.


It does:

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.

This text guarantees that after:

char *p = malloc(0);
char *q = malloc(0);

p == q *only* if both are null pointers (see the underlined "as if"
in the above quoted text), because this guarantee stands for nonzero
values of the argument. A strictly conforming program can trivially
check if this is the case and expose your hypothetical implementation
as non-conforming.

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

[ comp.std.c++ is moderated. To submit articles, try just posting with ]
[ your news-reader. If that fails, use mailto:st*****@ncar.ucar.edu ]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://www.jamesd.demon.co.uk/csc/faq.html ]
Nov 14 '05 #32

Fergus Henderson wrote:
Why would the implementation _care_ when the last free() occurs?


Almost all malloc implementations have storage overhead
associated with each live allocation, and they want to
liberate the overhead storage when they can. One could
concoct an implementation that had some weird special
handling for 0-sized allocations, but there is no reason
for doing so, and all implementations I know of that
support 0-sized allocations treat it the same way as any
positive-sized request (after adding 1 or not, depending
on the implementation).
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

[ comp.std.c++ is moderated. To submit articles, try just posting with ]
[ your news-reader. If that fails, use mailto:st*****@ncar.ucar.edu ]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://www.jamesd.demon.co.uk/csc/faq.html ]
Nov 14 '05 #33

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

Similar topics

32
by: John | last post by:
Hi all: When I run my code, I find that the memory that the code uses keeps increasing. I have a PC with 2G RAM running Debian linux. The code consumes 1.5G memory by the time it finishes...
6
by: Fred Zwarts | last post by:
Hello, I am trying to debug some complex debug code. In order to track the use of dynamically allocated memory, I replaced the standard global new and delete operators. (Not for changing the...
20
by: Jonas | last post by:
Hi, I'm 99 % sure that Standard C guarantees to do a memory move inside realloc() in case the new, returned memory block (address) is different than the original one. Can any C expert confirm...
8
by: vikram | last post by:
i have series of questions 1.How a c program is loaded in memory i mean the whats is the structure that the code segment?? data segment?? 2.When you say const int *p; where is p...
30
by: jimjim | last post by:
Hello, This is a simple question for you all, I guess . int main(){ double *g= new double; *g = 9; delete g; cout<< sizeof(g)<<" "<<sizeof(double)<<" "<<sizeof(*g)<<" "<<*g<<" "<<endl; *g =...
18
by: Ramasubbu Ramasubramanian XR (AS/EAB) | last post by:
What is memory leakage, could any one explain with sample code
25
by: Zeng | last post by:
I finally narrowed down my code to this situation, quite a few (not all) of my CMyClass objects got hold up after each run of this function via the simple webpage that shows NumberEd editbox. My...
2
by: Ashish | last post by:
hi all, I have been doing some performance testing of a asp_net website, to be hosted on a shared server .. as far as i understand every page when accessed first time is compiled and loaded in...
7
by: toton | last post by:
Hi, I have a STL vector of of characters and the character class has a Boost array of points. The things are vector<Characterchars; and class Character{ private: array<Point,Npoints; }; Now...
9
by: Hemal | last post by:
Hi All, I need to know the memory required by a c program. Is there any tool/utility which can give me the memory usage in terms of DATA segment, TEXT segment, BSS segment etc. I am working...
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: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
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?
0
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,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
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
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...
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.