473,326 Members | 2,588 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,326 software developers and data experts.

what malloc(0) should returns?

Hi,
Sorry if it might be a stupid question but what should returns
malloc(0) ?

void *ptr = malloc(0);

I am running gcc 3.3.5 and a non-null address is returned.

( in the compiler that I am currently implementing, NULL is returned.
Is it wrong ?)

or does an address should be always returned and
correspond to the current heap pointer ?

Dec 18 '06
82 30967
CBFalconer <cb********@yahoo.comwrites:
Harald van D?k wrote:
>Since
malloc(0) must (if it doesn't return NULL) behave as if a positive
argument is passed, except for dereferencing, you still get a pointer
to a region. In particular, if you convert malloc's result to a
character pointer, it means you're allowed to increment it at least
once. The fact that you're not allowed to access the value is
irrelevant, since the definition doesn't state otherwise.

Since it points to zero storage bytes, it has already been
incremented to one past the storage area.
No, it points to at least one byte. It's just that that byte, or
those bytes, cannot be accessed. The standard is quite clear
about this:

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.

I, at least, don't think that incrementing a pointer is
"access[ing] an object". Do you?
--
"When I have to rely on inadequacy, I prefer it to be my own."
--Richard Heathfield
Dec 19 '06 #51
Simon Biber <ne**@ralmin.ccwrites:
If you convert the pointer to char* and increment it, that
action is only valid if there is an object of at least one byte at the
address. So it could be argued that in effect you have used the
pointer to access an object.
The standard defines "access" like this:

3.1
1 access
execution-time action to read or modify the value of an object

Incrementing a pointer does not read or modify the value of the
object that the pointer points to (unless the pointer points to
itself, but that's not the case here).
--
"In My Egotistical Opinion, most people's C programs should be indented six
feet downward and covered with dirt." -- Blair P. Houghton
Dec 19 '06 #52
Richard Bos wrote:
Chris Dollin <ch**********@hp.comwrote:
>If an implementation chose to return the same pointer P for each malloc(0)
then realloc would need to know that P was operationally equal
to null, and hence in your code above the realloc would just mallocate
100 bytes for your convenience.

Ok, now try this one:

char *p1, *p2;
p1=malloc(0); p2=malloc(0);
p1=realloc(p1, 200);
p2=realloc(p2, 100);
p1[123]='?';
This code is fine, so long as the realloc on the third line succeeds,
otherwise the fifth line dereferences a null pointer.

If we're on an implementation that returns the same
pointer P for each malloc(0):
line 1: defines p1 and p2
line 2: p1 and p2 both gets the 'special' pointer P
line 3: realloc detects the P and returns malloc(200)
line 4: realloc detects the P and returns malloc(100)
line 5: the 124th byte of the block allocated on line 3 is set to '?'

If subsequent (non-free()d) calls to malloc(0) were allowed to deliver
identical pointers, that code would be allowed to make flying reindeer
come out of the North Pole.
Absolutely not. There is no undefined behaviour. The third line modifies
the value of p1 but it does not modify the value of p2. The value of p2
may still have the special pointer P, so the fourth line behaves exactly
like the third line did.

But Santa is just a cheap copy of the real,
Dutch, Saint Nicholas, and that code (bad use of realloc() excepted)
does not have undefined behaviour. Therefore, all pointers returned from
malloc(0) must be either null or not equal to any other pointer,
including ones obtained from other calls to malloc(0).
Faulty logic. The code has no undefined behaviour even if malloc(0) does
return the same pointer each time.

--
Simon.
Dec 19 '06 #53
Chris Torek wrote:
Since malloc() is a reserved function name, let me illustrate with
a different function-name. This also lets me use malloc() for the
"hard parts".

#include <stdlib.h>

static char magic;

void *nalloc(size_t size) {
if (size == 0)
return &magic; /* or: return NULL */
return malloc(size);
}

void nfree(void *p) {
if (p != &magic)
free(p);
}

void nrealloc(void *p, size_t size) {
if (p == &magic)
p = NULL;
if (size == 0) {
free(p);
return &magic; /* or: return NULL */
}
return realloc(p, size);
}
Looks good, except that nrealloc should return void *.
Given the obvious preconditions, the behavior of this code is
well-defined (which may suffice to label it "sensible"), but would
it suffice to replicate the Standard's requirements for malloc()?

I believe the answer is "no":

/* insert appropriate #include lines, etc., as needed */

#define Xalloc nalloc /* or malloc */
#define NAME "nalloc" /* or "malloc" */
#define Xfree nfree /* or free */

void check_it(void) {
void *p1 = Xalloc(0);
void *p2 = Xalloc(0);

if (p1 == NULL && p2 == NULL)
puts("OK: " NAME "(0) returned NULL each time");
else if (p1 == p2)
puts("FAIL: p1 == p2, but p1 and p2 are not NULL");
else {
puts("OK: alloc(0), called twice, returned two different")
puts("non-NULLs, or one non-NULL and one NULL");
}
Xfree(p1);
Xfree(p2);
}

If we use this check_it() routine on nalloc(), it will print the
"FAIL" line, because p1 and p2 are equal, yet at least one of the
two pointers is not NULL (in fact both point to the "magic" byte).
Yes. Though if there weren't the explicit restriction in the standard:
"Each such allocation shall yield a pointer to an object disjoint
from any other object."
Then this behaviour of nalloc would be acceptable as a replacement for
malloc.

--
Simon.
Dec 19 '06 #54
"Keith Thompson" <ks***@mib.orgwrote in message
news:ln************@nuthaus.mib.org...
In my opinion, the behavior defined by the standard for malloc(0) is
not particularly useful.
As with many C oddities, it was more an issue of documenting what
existing pre-ANSI C implementations did, not specifying ideal behavior.

A lot of things in C would be very different if it had been specified
fully before implementations were written -- but it never would have
caught on.

S

--
Stephen Sprunk "God does not play dice." --Albert Einstein
CCIE #3723 "God is an inveterate gambler, and He throws the
K5SSS dice at every possible opportunity." --Stephen Hawking
--
Posted via a free Usenet account from http://www.teranews.com

Dec 20 '06 #55
"Random832" <ra****@random.yi.orgwrote in message
news:sl*******************@rlaptop.random.yi.org.. .
2006-12-19 <45***************@yahoo.com>,
CBFalconer wrote:
>Random832 wrote:
>>CBFalconer wrote:

The standard requires malloced pointers to objects be
distinct. After the free(p) p is no longer a pointer to an object.

In what sense is the non-null result of malloc(0) a pointer to an
object anyway?

In the sense that it behaves that way. However you can't legally
dereference it, just as you can't alter an anonymous char string.

To what object does it point?
To the zero-byte object that malloc() allocated :)

Of course, asking for details about a zero-byte object is pointless,
since an object of zero bytes has no properties other than an address.
It's like asking about properties of a object of type void (and I don't
mean void*).

Harald's comment about being able to increment a pointer to a zero-byte
object is interesting, though. Should that be legal? IMHO, the pointer
already points to the byte after the end of the object when you get it,
and it'd be UB to try to increment it -- or decrement it.

S

--
Stephen Sprunk "God does not play dice." --Albert Einstein
CCIE #3723 "God is an inveterate gambler, and He throws the
K5SSS dice at every possible opportunity." --Stephen Hawking
--
Posted via a free Usenet account from http://www.teranews.com

Dec 20 '06 #56
2006-12-19 <45**********@news.peopletelecom.com.au>,
Simon Biber wrote:
Chris Torek wrote:
>Since malloc() is a reserved function name, let me illustrate with
a different function-name. This also lets me use malloc() for the
"hard parts".

#include <stdlib.h>

static char magic;

void *nalloc(size_t size) {
if (size == 0)
return &magic; /* or: return NULL */
return malloc(size);
}

void nfree(void *p) {
if (p != &magic)
free(p);
}

void nrealloc(void *p, size_t size) {
if (p == &magic)
p = NULL;
if (size == 0) {
free(p);
return &magic; /* or: return NULL */
}
return realloc(p, size);
}

Looks good, except that nrealloc should return void *.
>Given the obvious preconditions, the behavior of this code is
well-defined (which may suffice to label it "sensible"), but would
it suffice to replicate the Standard's requirements for malloc()?

I believe the answer is "no":

/* insert appropriate #include lines, etc., as needed */

#define Xalloc nalloc /* or malloc */
#define NAME "nalloc" /* or "malloc" */
#define Xfree nfree /* or free */

void check_it(void) {
void *p1 = Xalloc(0);
void *p2 = Xalloc(0);

if (p1 == NULL && p2 == NULL)
puts("OK: " NAME "(0) returned NULL each time");
else if (p1 == p2)
puts("FAIL: p1 == p2, but p1 and p2 are not NULL");
else {
puts("OK: alloc(0), called twice, returned two different")
puts("non-NULLs, or one non-NULL and one NULL");
}
Xfree(p1);
Xfree(p2);
}
>
If we use this check_it() routine on nalloc(), it will print the
"FAIL" line, because p1 and p2 are equal, yet at least one of the
two pointers is not NULL (in fact both point to the "magic" byte).

Yes. Though if there weren't the explicit restriction in the standard:
"Each such allocation shall yield a pointer to an object disjoint
from any other object."
All zero-length objects are disjoint from one another. Or at least as
many as the number of angels that can dance on the head of a pin.
Then this behaviour of nalloc would be acceptable as a replacement for
malloc.
Dec 20 '06 #57

Keith Thompson wrote:
*sniped* <

A quick test of a few systems I happen to have immediate access to
shows that all of them either return a null pointer, or return
distinct values on two successive calls to malloc(0).

As for why this is required, C99 7.20.3p1 says:

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.

One aspect of the behavior of malloc() with a non-zero size is that
successive calls return unique values. My interpretation is that this
same behavior is required for non-null results of malloc(0).

The simplest way to implement this is to quietly translate "malloc(0)"
to "malloc(1)".
Does this imply that if an implementation makes malloc(0) return a
non-null pointer, this pointer shall be free()d?

Dec 20 '06 #58
WaterWalk wrote:
Keith Thompson wrote:
>*sniped* <

A quick test of a few systems I happen to have immediate access to
shows that all of them either return a null pointer, or return
distinct values on two successive calls to malloc(0).

As for why this is required, C99 7.20.3p1 says:

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.

One aspect of the behavior of malloc() with a non-zero size is
that successive calls return unique values. My interpretation is
that this same behavior is required for non-null results of
malloc(0).

The simplest way to implement this is to quietly translate
"malloc(0)" to "malloc(1)".

Does this imply that if an implementation makes malloc(0) return
a non-null pointer, this pointer shall be free()d?
Yes. Implied by the fact that the malloc subsystem has to keep
track of allocations somewhere, and this necessarily consumes some
sort of storage. free then releases any such.

--
Chuck F (cbfalconer at maineline dot net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home.att.net>
Dec 20 '06 #59
"Stephen Sprunk" <st*****@sprunk.orgwrites:
"Random832" <ra****@random.yi.orgwrote in message
news:sl*******************@rlaptop.random.yi.org.. .
>2006-12-19 <45***************@yahoo.com>,
CBFalconer wrote:
>>Random832 wrote:
CBFalconer wrote:

The standard requires malloced pointers to objects be
distinct. After the free(p) p is no longer a pointer to an object.

In what sense is the non-null result of malloc(0) a pointer to an
object anyway?

In the sense that it behaves that way. However you can't legally
dereference it, just as you can't alter an anonymous char string.

To what object does it point?

To the zero-byte object that malloc() allocated :)
No, to the at-least-one-byte object that malloc() allocated (but that
you're not allowed to access).
Of course, asking for details about a zero-byte object is pointless,
since an object of zero bytes has no properties other than an
address. It's like asking about properties of a object of type void
(and I don't mean void*).
There are no objects of type void.
Harald's comment about being able to increment a pointer to a
zero-byte object is interesting, though. Should that be legal? IMHO,
the pointer already points to the byte after the end of the object
when you get it, and it'd be UB to try to increment it -- or decrement
it.
C doesn't support zero-byte objects.

--
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.
Dec 20 '06 #60
"Stephen Sprunk" <st*****@sprunk.orgwrites:
"Keith Thompson" <ks***@mib.orgwrote in message
news:ln************@nuthaus.mib.org...
>In my opinion, the behavior defined by the standard for malloc(0) is
not particularly useful.

As with many C oddities, it was more an issue of documenting what
existing pre-ANSI C implementations did, not specifying ideal behavior.

A lot of things in C would be very different if it had been specified
fully before implementations were written -- but it never would have
caught on.
Agreed. I think the gist of the description is that malloc(0) isn't
allowed to blow up; the standard goes into some (possibly unnecessary)
detail about *how* it's not allowed to blow up.

But it seems to me the C89 standard *could* have nailed this down more
tightly than it did. It also mandated that free(NULL) does nothing;
in some existing implementations at the time, it would crash.
Mandating that malloc(0) returns a unique non-null pointer (unless
memory has run out) would have been just as easy; implementations
would just have had to change to meet the new requirement.

It's too late now, I suppose.

--
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.
Dec 20 '06 #61
"WaterWalk" <to********@163.comwrites:
Keith Thompson wrote:
>*sniped* <

A quick test of a few systems I happen to have immediate access to
shows that all of them either return a null pointer, or return
distinct values on two successive calls to malloc(0).

As for why this is required, C99 7.20.3p1 says:

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.

One aspect of the behavior of malloc() with a non-zero size is that
successive calls return unique values. My interpretation is that this
same behavior is required for non-null results of malloc(0).

The simplest way to implement this is to quietly translate "malloc(0)"
to "malloc(1)".

Does this imply that if an implementation makes malloc(0) return a
non-null pointer, this pointer shall be free()d?
What do you mean by "shall"?

There's no requirement to free() any malloc()ed pointer; terminating a
program without free()ing anything is perfectly acceptable as far as
the standard is concerned.

It's true that the result returned by malloc(0) *may* be passed to
free().

--
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.
Dec 20 '06 #62
On Tue, 19 Dec 2006 22:22:50 +0100, "Serve Laurijssen" <se*@n.tk>
wrote:
>
"jaysome" <ja*****@hotmail.comwrote in message
news:f2********************************@4ax.com.. .
>On Mon, 18 Dec 2006 16:29:02 +0000, Richard Heathfield
<rj*@see.sig.invalidwrote:
The last sentence in the above quote is meant for your own good, and
has nothing to do with how the OS might misbehave (though it could).
All WIN32 platforms--95/98/ME/NT/2K/XP/2003/Vista/32/64--gracefully
handle null pointer dereferences.

depends if you call access violations graceful ;)
To me, "graceful" in Windows means no BSOD, just like "graceful" in
*NIX means no kernel panic :^)

Best regards
--
jay
Dec 20 '06 #63
CBFalconer wrote:
Chris Dollin wrote:
>CBFalconer wrote:
>>Chris Dollin wrote:
>>>I am not arguing that the choice "malloc(0) always returns the
same pointer" would be /sensible/ if it were legal, just that
it could be made to work consistently.

No it couldn't. Think about pointer comparisons. Then think about
what other anomalies could exist. But one is enough to show it is
a bad idea.

I'm thinking, but I can't see an anomaly. I'm probably just being
dim.

You snipped one that I showed earlier.
Hell's teeth, man, cut me some slack -- it's nearly Christmas. I
/did not see/ an anomaly. Write the thing in a reply and explain
what the problem is. It's probably too obvious for me to be able
to see it without help.

--
Chris "HO. HO. HO." Dollin
Nit-picking is best done among friends.

Dec 20 '06 #64
Chris Torek wrote:
>>Chris Dollin wrote:
I am not arguing that the choice "malloc(0) always returns the
same pointer" would be /sensible/ if it were legal, just that
it could be made to work consistently.
>>CBFalconer wrote:
>>No it couldn't. Think about pointer comparisons. Then think about
what other anomalies could exist. But one is enough to show it is
a bad idea.

In article <em**********@murdoch.hpl.hp.com>
Chris Dollin <ch**********@hp.comwrote:
>>I'm thinking, but I can't see an anomaly. I'm probably just being
dim.

Since malloc() is a reserved function name, let me illustrate with
a different function-name. This also lets me use malloc() for the
"hard parts".
(fx:snip)
Given the obvious preconditions, the behavior of this code is
well-defined (which may suffice to label it "sensible"), but would
it suffice to replicate the Standard's requirements for malloc()?
No, because the Standard says otherwise -- but CB seemed to be
arguing that even without that explicit requirement the unique
magic pointer approach couldn't be made consistent.

--
Chris "HO. HO. HO." Dollin
"I'm still here and I'm holding the answers" - Karnataka, /Love and Affection/

Dec 20 '06 #65
Chris Dollin wrote:
CBFalconer wrote:
>Chris Dollin wrote:
>>CBFalconer wrote:
Chris Dollin wrote:

I am not arguing that the choice "malloc(0) always returns the
same pointer" would be /sensible/ if it were legal, just that
it could be made to work consistently.

No it couldn't. Think about pointer comparisons. Then think about
what other anomalies could exist. But one is enough to show it is
a bad idea.

I'm thinking, but I can't see an anomaly. I'm probably just being
dim.

You snipped one that I showed earlier.

Hell's teeth, man, cut me some slack -- it's nearly Christmas. I
/did not see/ an anomaly. Write the thing in a reply and explain
what the problem is. It's probably too obvious for me to be able
to see it without help.
<Requoted>
>>p1 = malloc(0); p2 = malloc(0); p2 = realloc(p2, 100);

(Ignore the misuse of realloc). Now, if p2 had free space above
it, p2 might be unchanged. However p1 is still pointing to zero
bytes. You would get very funny results by depending on "if
(p1 == p2)".
</requoted>

The anomaly appears if the results of the malloc calls are non-NULL
and not distinct, i.e. non-compliant.

--
Chuck F (cbfalconer at maineline dot net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home.att.net>
Dec 20 '06 #66
2006-12-20 <45***************@yahoo.com>,
CBFalconer wrote:
Chris Dollin wrote:
>CBFalconer wrote:
>>Chris Dollin wrote:
CBFalconer wrote:
Chris Dollin wrote:

>I am not arguing that the choice "malloc(0) always returns the
>same pointer" would be /sensible/ if it were legal, just that
>it could be made to work consistently.
>
No it couldn't. Think about pointer comparisons. Then think about
what other anomalies could exist. But one is enough to show it is
a bad idea.

I'm thinking, but I can't see an anomaly. I'm probably just being
dim.

You snipped one that I showed earlier.

Hell's teeth, man, cut me some slack -- it's nearly Christmas. I
/did not see/ an anomaly. Write the thing in a reply and explain
what the problem is. It's probably too obvious for me to be able
to see it without help.

<Requoted>
>>>p1 = malloc(0); p2 = malloc(0); p2 = realloc(p2, 100);

(Ignore the misuse of realloc). Now, if p2 had free space above
it, p2 might be unchanged.
Or it might NOT be unchanged, since we've established that in the
implementation method being discussed, malloc(0) is a special case and
not a normal heap pointer.
>>>However p1 is still pointing to zero
bytes. You would get very funny results by depending on "if
(p1 == p2)".
</requoted>

The anomaly appears if the results of the malloc calls are non-NULL
and not distinct, i.e. non-compliant.
Dec 20 '06 #67

Keith Thompson wrote:
"WaterWalk" <to********@163.comwrites:
Keith Thompson wrote:
*sniped* <

A quick test of a few systems I happen to have immediate access to
shows that all of them either return a null pointer, or return
distinct values on two successive calls to malloc(0).

As for why this is required, C99 7.20.3p1 says:

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.

One aspect of the behavior of malloc() with a non-zero size is that
successive calls return unique values. My interpretation is that this
same behavior is required for non-null results of malloc(0).

The simplest way to implement this is to quietly translate "malloc(0)"
to "malloc(1)".
Does this imply that if an implementation makes malloc(0) return a
non-null pointer, this pointer shall be free()d?

What do you mean by "shall"?

There's no requirement to free() any malloc()ed pointer; terminating a
program without free()ing anything is perfectly acceptable as far as
the standard is concerned.

It's true that the result returned by malloc(0) *may* be passed to
free().
Oh, what I mean is: if a lot of malloc(0) is called and the returned
results are not free()d, then this is still memory leak. Am I right?

Dec 24 '06 #68
WaterWalk wrote:
Keith Thompson wrote:
"WaterWalk" <to********@163.comwrites:
Does this imply that if an implementation makes malloc(0) return a
non-null pointer, this pointer shall be free()d?
What do you mean by "shall"?

There's no requirement to free() any malloc()ed pointer; terminating a
program without free()ing anything is perfectly acceptable as far as
the standard is concerned.

It's true that the result returned by malloc(0) *may* be passed to
free().

Oh, what I mean is: if a lot of malloc(0) is called and the returned
results are not free()d, then this is still memory leak. Am I right?
Yes, if you do not free a non-NULL result from malloc, even with a size
of zero, you have a memory leak.

Dec 24 '06 #69
Harald van D?k wrote:
WaterWalk wrote:
>Keith Thompson wrote:
>>"WaterWalk" <to********@163.comwrites:

Does this imply that if an implementation makes malloc(0) return
a non-null pointer, this pointer shall be free()d?

What do you mean by "shall"?

There's no requirement to free() any malloc()ed pointer;
terminating a program without free()ing anything is perfectly
acceptable as far as the standard is concerned.

It's true that the result returned by malloc(0) *may* be passed
to free().

Oh, what I mean is: if a lot of malloc(0) is called and the
returned results are not free()d, then this is still memory leak.
Am I right?

Yes, if you do not free a non-NULL result from malloc, even with
a size of zero, you have a memory leak.
If you stop to think about it the system has to keep track of
allocations somewhere, even in the case of a zero size returning
non-NULL, and the only way to signal the release of that
information is via free.

--
Merry Christmas, Happy Hanukah, Happy New Year
Joyeux Noel, Bonne Annee.
Chuck F (cbfalconer at maineline dot net)
<http://cbfalconer.home.att.net>
Dec 24 '06 #70
CBFalconer wrote:
Harald van D?k wrote:
>WaterWalk wrote:
>>Keith Thompson wrote:
"WaterWalk" <to********@163.comwrites:

Does this imply that if an implementation makes malloc(0) return
a non-null pointer, this pointer shall be free()d?
What do you mean by "shall"?

There's no requirement to free() any malloc()ed pointer;
terminating a program without free()ing anything is perfectly
acceptable as far as the standard is concerned.

It's true that the result returned by malloc(0) *may* be passed
to free().
Oh, what I mean is: if a lot of malloc(0) is called and the
returned results are not free()d, then this is still memory leak.
Am I right?
Yes, if you do not free a non-NULL result from malloc, even with
a size of zero, you have a memory leak.

If you stop to think about it the system has to keep track of
allocations somewhere, even in the case of a zero size returning
non-NULL, and the only way to signal the release of that
information is via free.
Hi Chuck. Merry Christmas.

If I were King, the argument to malloc would be defined 0. An argument
0 would force a malloc failure and a NULL return. free(NULL) is harmless
and so, voila, no problem.

--
Joe Wright
"Everything should be made as simple as possible, but not simpler."
--- Albert Einstein ---
Dec 24 '06 #71
Joe Wright wrote:
CBFalconer wrote:
.... snip ...
>>
If you stop to think about it the system has to keep track of
allocations somewhere, even in the case of a zero size returning
non-NULL, and the only way to signal the release of that
information is via free.

If I were King, the argument to malloc would be defined 0.
An argument 0 would force a malloc failure and a NULL return.
free(NULL) is harmless and so, voila, no problem.
Bad idea. The system may be used to process variable length data,
which may be empty. This size can be coming in as a parameter to
some routine or other. You don't want to have to test all sorts of
special cases in that routine. Although with the existing C
standard you probably have to:

if (!sz) sz++;
if (!(p = malloc(sz)) failure();
else carryon();

which is why I consider systems that return distinct pointers for
malloc(0) superior. They will forgive forgetting to make the
preliminary check.

--
Merry Christmas, Happy Hanukah, Happy New Year
Joyeux Noel, Bonne Annee.
Chuck F (cbfalconer at maineline dot net)
<http://cbfalconer.home.att.net>
Dec 24 '06 #72
CBFalconer <cb********@yahoo.comwrites:
Joe Wright wrote:
>CBFalconer wrote:
... snip ...
>>>
If you stop to think about it the system has to keep track of
allocations somewhere, even in the case of a zero size returning
non-NULL, and the only way to signal the release of that
information is via free.

If I were King, the argument to malloc would be defined 0.
An argument 0 would force a malloc failure and a NULL return.
free(NULL) is harmless and so, voila, no problem.

Bad idea. The system may be used to process variable length data,
which may be empty. This size can be coming in as a parameter to
some routine or other. You don't want to have to test all sorts of
special cases in that routine. Although with the existing C
standard you probably have to:

if (!sz) sz++;
if (!(p = malloc(sz)) failure();
else carryon();

which is why I consider systems that return distinct pointers for
malloc(0) superior. They will forgive forgetting to make the
preliminary check.
In other words, they will fail to diagnose the failure to make the
required check. How friendly.

If I were King, the behavior of malloc(0) would be well-defined. I
might flip a coin to decide *how* it's defined. Heads (i.e., my
portrait) means it's equivalent to malloc(1), except that the pointer
may not be dereferenced; tails means malloc(0) returns a null pointer.
The coin toss would occur only once, and would determine the rule to
be written in the standard. Sufficient bribery might induce me to use
a weighted coin.

--
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.
Dec 24 '06 #73
"Keith Thompson" <ks***@mib.orgwrote in message
news:ln************@nuthaus.mib.org...
CBFalconer <cb********@yahoo.comwrites:
>Joe Wright wrote:
>>CBFalconer wrote:
... snip ...
>>>>
If you stop to think about it the system has to keep track of
allocations somewhere, even in the case of a zero size returning
non-NULL, and the only way to signal the release of that
information is via free.

If I were King, the argument to malloc would be defined 0.
An argument 0 would force a malloc failure and a NULL return.
free(NULL) is harmless and so, voila, no problem.

Bad idea. The system may be used to process variable length data,
which may be empty. This size can be coming in as a parameter to
some routine or other. You don't want to have to test all sorts of
special cases in that routine. Although with the existing C
standard you probably have to:

if (!sz) sz++;
if (!(p = malloc(sz)) failure();
else carryon();

which is why I consider systems that return distinct pointers for
malloc(0) superior. They will forgive forgetting to make the
preliminary check.

In other words, they will fail to diagnose the failure to make the
required check. How friendly.

If I were King, the behavior of malloc(0) would be well-defined. I
might flip a coin to decide *how* it's defined. Heads (i.e., my
portrait) means it's equivalent to malloc(1), except that the pointer
may not be dereferenced; tails means malloc(0) returns a null pointer.
The coin toss would occur only once, and would determine the rule to
be written in the standard. Sufficient bribery might induce me to use
a weighted coin.
But what happened instead was much worse. I fought for several meetings
to have malloc(0) return a unique non-null pointer -- just as the Unix
implementation had been doing since day one, not to mention ours (then
Whitesmiths) and all others I knew about. As CBFalconer observed, a
zero-size dynamic array is a naturally occuring thing, just like while
loops that loop zero times. But for some reason Larry Rosler argued
vehemently for malloc(0) being an error, even though this was not in
the best interests of Bell Labs, his employer. By the time I'd convinced
Rosler of my view, most of the committee had grown tired of the whole
debate. So they settled on the worst possible "compromise" -- neither
behavior is guaranteed.

A coin toss would have been a better resolution.

P.J. Plauger
Dinkumware, Ltd.
http://www.dinkumware.com
Dec 25 '06 #74
"P.J. Plauger" wrote:
>
.... snip ...
>
But what happened instead was much worse. I fought for several meetings
to have malloc(0) return a unique non-null pointer -- just as the Unix
implementation had been doing since day one, not to mention ours (then
Whitesmiths) and all others I knew about. As CBFalconer observed, a
zero-size dynamic array is a naturally occuring thing, just like while
loops that loop zero times. But for some reason Larry Rosler argued
vehemently for malloc(0) being an error, even though this was not in
the best interests of Bell Labs, his employer. By the time I'd convinced
Rosler of my view, most of the committee had grown tired of the whole
debate. So they settled on the worst possible "compromise" -- neither
behavior is guaranteed.

A coin toss would have been a better resolution.
Well, at least now we can point disdainfully at the actual cause of
the problem :-) We can name it the Rosler curse.

BTW, to answer Keiths objection, my nmalloc for DJGPP includes a
provision (non-standard) for injecting run-time hooks, which can
change that behaviour.

--
Merry Christmas, Happy Hanukah, Happy New Year
Joyeux Noel, Bonne Annee.
Chuck F (cbfalconer at maineline dot net)
<http://cbfalconer.home.att.net>
Dec 25 '06 #75
In article <vb******************************@giganews.com>,
P.J. Plauger <pj*@dinkumware.comwrote:
>So they settled on the worst possible "compromise" -- neither
behavior is guaranteed.
I agree distinct pointers would be better, but the current behaviour
does at least cover the common case: you can malloc an array without
regard for it being possibly empty, and realloc it safely, getting a
real unique value once you need some real memory.

-- Richard

--
"Consideration shall be given to the need for as many as 32 characters
in some alphabets" - X3.4, 1963.
Dec 25 '06 #76
"Richard Tobin" <ri*****@cogsci.ed.ac.ukwrote in message
news:em***********@pc-news.cogsci.ed.ac.uk...
In article <vb******************************@giganews.com>,
P.J. Plauger <pj*@dinkumware.comwrote:
>>So they settled on the worst possible "compromise" -- neither
behavior is guaranteed.

I agree distinct pointers would be better, but the current behaviour
does at least cover the common case: you can malloc an array without
regard for it being possibly empty, and realloc it safely, getting a
real unique value once you need some real memory.
Uh, no. One of the arguments in favor of permitting malloc(0) to be
erroneous was to let some systems diagnose, even trap out, on such
a call. So it's never portably safe to call malloc(0), and it's never
a sure thing that it'll be treated as an error. Everybody loses.

P.J. Plauger
Dinkumware, Ltd.
http://www.dinkumware.com
Dec 25 '06 #77
In article <XJ******************************@giganews.com>,
P.J. Plauger <pj*@dinkumware.comwrote:
>I agree distinct pointers would be better, but the current behaviour
does at least cover the common case: you can malloc an array without
regard for it being possibly empty, and realloc it safely, getting a
real unique value once you need some real memory.
>Uh, no. One of the arguments in favor of permitting malloc(0) to be
erroneous was to let some systems diagnose, even trap out, on such
a call. So it's never portably safe to call malloc(0), and it's never
a sure thing that it'll be treated as an error. Everybody loses.

I think you're misremembering. The standard requires malloc(0) to
return either a distinct pointer or NULL. It's not allowed to treat
it as an error.

-- Richard
--
"Consideration shall be given to the need for as many as 32 characters
in some alphabets" - X3.4, 1963.
Dec 25 '06 #78
"Richard Tobin" <ri*****@cogsci.ed.ac.ukwrote in message
news:em***********@pc-news.cogsci.ed.ac.uk...
In article <XJ******************************@giganews.com>,
P.J. Plauger <pj*@dinkumware.comwrote:
>>I agree distinct pointers would be better, but the current behaviour
does at least cover the common case: you can malloc an array without
regard for it being possibly empty, and realloc it safely, getting a
real unique value once you need some real memory.
>>Uh, no. One of the arguments in favor of permitting malloc(0) to be
erroneous was to let some systems diagnose, even trap out, on such
a call. So it's never portably safe to call malloc(0), and it's never
a sure thing that it'll be treated as an error. Everybody loses.


I think you're misremembering. The standard requires malloc(0) to
return either a distinct pointer or NULL. It's not allowed to treat
it as an error.
So it seems. The C Standard didn't always end up saying exactly
what the committee decided by consensus.

P.J. Plauger
Dinkumware, Ltd.
http://www.dinkumware.com
Dec 25 '06 #79
av
On Sun, 24 Dec 2006 11:33:24 -0800, Keith Thompson wrote:
>CBFalconer <cb********@yahoo.comwrites:
>Joe Wright wrote:
>>CBFalconer wrote:
... snip ...
>>>If you stop to think about it the system has to keep track of
allocations somewhere, even in the case of a zero size returning
non-NULL, and the only way to signal the release of that
information is via free.

If I were King, the argument to malloc would be defined 0.
An argument 0 would force a malloc failure and a NULL return.
free(NULL) is harmless and so, voila, no problem.

Bad idea. The system may be used to process variable length data,
which may be empty. This size can be coming in as a parameter to
some routine or other. You don't want to have to test all sorts of
special cases in that routine. Although with the existing C
standard you probably have to:

if (!sz) sz++;
if (!(p = malloc(sz)) failure();
else carryon();

which is why I consider systems that return distinct pointers for
malloc(0) superior. They will forgive forgetting to make the
preliminary check.

In other words, they will fail to diagnose the failure to make the
required check. How friendly.

If I were King, the behavior of malloc(0) would be well-defined. I
might flip a coin to decide *how* it's defined. Heads (i.e., my
portrait) means it's equivalent to malloc(1), except that the pointer
may not be dereferenced; tails means malloc(0) returns a null pointer.
The coin toss would occur only once, and would determine the rule to
be written in the standard. Sufficient bribery might induce me to use
a weighted coin.
why standard says should be: malloc(0)==0 or malloc(0) has to point
some data whose access is illegal

why malloc(0)!=0 has to point to some data
(i.e. "(char*)malloc(0)"
has some memory, but access to it is illegal)?

in how i see
malloc(0) has to return "p" pointer
|header|
^
p
where *(char*)p has to segfault and p should not have memory reserved
for programme
Dec 25 '06 #80
av
On Mon, 25 Dec 2006 17:45:54 +0100, av wrote:
>in how i see
malloc(0) has to return "p" pointer
|header|
^
p
where *(char*)p has to segfault and p should not have memory reserved
for programme
wrong (above mean each malloc(0) has its pointer different)
where *(char*)p=1 can segfault, or free() function can possibly see
the error when it free p
Dec 25 '06 #81

CBFalconer wrote:
Joe Wright wrote:
CBFalconer wrote:
... snip ...
>
If you stop to think about it the system has to keep track of
allocations somewhere, even in the case of a zero size returning
non-NULL, and the only way to signal the release of that
information is via free.
If I were King, the argument to malloc would be defined 0.
An argument 0 would force a malloc failure and a NULL return.
free(NULL) is harmless and so, voila, no problem.

Bad idea. The system may be used to process variable length data,
which may be empty. This size can be coming in as a parameter to
some routine or other. You don't want to have to test all sorts of
special cases in that routine. Although with the existing C
standard you probably have to:

if (!sz) sz++;
if (!(p = malloc(sz)) failure();
else carryon();

which is why I consider systems that return distinct pointers for
malloc(0) superior. They will forgive forgetting to make the
preliminary check.
I don't think it's a good idea. For even if sz in malloc(sz) is bigger
than zero, you still have to test if the malloc fails, since it is
always possible that not enough memory exists.

Dec 26 '06 #82
WaterWalk wrote:
CBFalconer wrote:
.... snip ...
>>
Bad idea. The system may be used to process variable length data,
which may be empty. This size can be coming in as a parameter to
some routine or other. You don't want to have to test all sorts of
special cases in that routine. Although with the existing C
standard you probably have to:

if (!sz) sz++;
if (!(p = malloc(sz)) failure();
else carryon();

which is why I consider systems that return distinct pointers for
malloc(0) superior. They will forgive forgetting to make the
preliminary check.

I don't think it's a good idea. For even if sz in malloc(sz) is
bigger than zero, you still have to test if the malloc fails,
since it is always possible that not enough memory exists.
I think you missed the word 'preliminary' above. That is the check
on sz.

--
Merry Christmas, Happy Hanukah, Happy New Year
Joyeux Noel, Bonne Annee.
Chuck F (cbfalconer at maineline dot net)
<http://cbfalconer.home.att.net>
Dec 26 '06 #83

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

Similar topics

6
by: Peter Michaux | last post by:
Suppose I have implemented a language with garbage collection in C. I have wrapped malloc in my own C function. If malloc returns NULL then I can run the garbage collector and then try malloc...
1
by: Eswarranjani | last post by:
what is $$ value..? what it returns in shell scripts..?
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

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.