By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
459,977 Members | 1,617 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 459,977 IT Pros & Developers. It's quick & easy.

call to malloc with size 0

P: n/a
Neo
Hi Folks,

I've a simple qestion related to dynamic memory allocation in C here is the
code:

#include <stdio.h>

int main()

{

char *p;

if( (p=(char*)malloc(0)) == NULL)

printf("NULL\n");

else

printf("Valid Pointer\n");

return 0;

}

Output : "Valid Pointer"

Why this code fragment returns a valid pointer to a memory block???

-Neo


Nov 14 '05 #1
Share this Question
Share on Google+
54 Replies


P: n/a
In article <30*************@uni-berlin.de>, ti***************@yahoo.com
says...
Why this code fragment returns a valid pointer to a memory block???

-Neo


I've seen this before. Some versions of UNIX will return an error,
others will return a valid pointer. I'm not sure which is correct but I
found the 2nd situation to be more common and more useful as you don't
have to code round it - I've got a few +1's in some code just to
guarentee a valid pointer which happens to contain nothing. That way I
know the pointer has been initialised even it doesn't contain anything.
It's working like a flag as well as a place to store results.

--
http://www.beluga.freeserve.co.uk
Nov 14 '05 #2

P: n/a

"Neo" <ti***************@yahoo.com> wrote in message
news:30*************@uni-berlin.de...
Hi Folks,

I've a simple qestion related to dynamic memory allocation in C here is the code:

#include <stdio.h>

int main()

{

char *p;

if( (p=(char*)malloc(0)) == NULL)

printf("NULL\n");

else

printf("Valid Pointer\n");

return 0;

}

Output : "Valid Pointer"

Why this code fragment returns a valid pointer to a memory block???

-Neo

See what the standard says

4.10.3 Memory management functions:

If the size of the space requested is zero, the behavior is
*implementation-defined*; the value returned shall be either a null
pointer or a unique pointer.

So check in your impelementation documents for answer !

- Ravi

Nov 14 '05 #3

P: n/a
On Wed, 17 Nov 2004 15:49:10 +0530, Ravi Uday wrote:

"Neo" <ti***************@yahoo.com> wrote in message
news:30*************@uni-berlin.de...
Hi Folks,

I've a simple qestion related to dynamic memory allocation in C here is

the
code:

#include <stdio.h>

int main()

{

char *p;

if( (p=(char*)malloc(0)) == NULL)
Get rid of the cast. The compiler should then complain, which is
good because the code is broken. Adding the cast doesn't fix the
code, it just stops the compiler complaining about the problem.

The problem is that you don't have a valid declaration for malloc()
in scope when you call it. In that case the compiler assumes
that malloc() returns int, but it doesn't, it returns void *. All
standard library functions are provided with a declaration in
the appropriate standard header. For malloc() that is <stdlib.h>.

printf("NULL\n");

else

printf("Valid Pointer\n");

return 0;

}

Output : "Valid Pointer"

Why this code fragment returns a valid pointer to a memory block???
Your code invokes undefined behaviour due to the invalid cast, so anything
can happen. Once that's fixed the issue is as below i.e. the compiler does
it because the standard says it can.

-Neo

See what the standard says

4.10.3 Memory management functions:

If the size of the space requested is zero, the behavior is
*implementation-defined*; the value returned shall be either a null
pointer or a unique pointer.

So check in your impelementation documents for answer !


Lawrence
Nov 14 '05 #4

P: n/a

"Ravi Uday" <ra******@gmail.com> wrote in message
news:1100686594.274808@sj-nntpcache-5...

"Neo" <ti***************@yahoo.com> wrote in message
news:30*************@uni-berlin.de...
Hi Folks,

I've a simple qestion related to dynamic memory allocation in C here is

the
code:

#include <stdio.h>

int main()

{

char *p;

if( (p=(char*)malloc(0)) == NULL)

printf("NULL\n");

else

printf("Valid Pointer\n");

return 0;

}

Output : "Valid Pointer"

Why this code fragment returns a valid pointer to a memory block???

-Neo

See what the standard says

4.10.3 Memory management functions:

If the size of the space requested is zero, the behavior is
*implementation-defined*; the value returned shall be either a null
pointer or a unique pointer.

So check in your impelementation documents for answer !

- Ravi


<OT>

Why didn't they put it in the standard that a null pointer must be returned?
It seems like the right/logical behaviour for calling malloc on size 0 and
avoids any confusion.

</OT>
Nov 14 '05 #5

P: n/a
Peter Smithson <pg**********************@yahoo.co.uk> wrote:
In article <30*************@uni-berlin.de>, ti***************@yahoo.com
says...
Why this code fragment returns a valid pointer to a memory block???
I've seen this before. Some versions of UNIX will return an error,


By which, I hope, you mean a null pointer, since causing a segfault or a
signal for malloc(0) is not conforming.
others will return a valid pointer. I'm not sure which is correct


Either.

Richard
Nov 14 '05 #6

P: n/a
On Wed, 17 Nov 2004 07:45:50 -0500, Method Man wrote:
....
<OT>

Why didn't they put it in the standard that a null pointer must be returned?
It seems like the right/logical behaviour for calling malloc on size 0 and
avoids any confusion.

</OT>


Probably because there were existing implementations for both types of
result. I don't think it makes much practical difference, I can only think
of 2 uses for this:

1. Creating a unique pointer value which compares unequal to all others.
For this to work you would need to prefer the non-null return behaviour.
Of course you can use malloc(1) for this. However malloc() can always fail
so it could return null for any call.

2. You are setting up an object whick you might extend later using
realloc(). However whether malloc(0) return null or not is immaterial to
this, either result can be passed to realloc(). So the latitude given by
the standard is harmless here. Of course you have the issue of freeing the
"object" for a non-null return.

Lawrence
Nov 14 '05 #7

P: n/a
Lawrence Kirby <lk****@netactive.co.uk> wrote:
2. You are setting up an object whick you might extend later using
realloc(). However whether malloc(0) return null or not is immaterial to
this, either result can be passed to realloc(). So the latitude given by
the standard is harmless here. Of course you have the issue of freeing the
"object" for a non-null return.


Even that is not a problem, since free(0) is harmless. No matter what
you get from malloc(), you can free() it.

Richard
Nov 14 '05 #8

P: n/a
On Wed, 17 Nov 2004 13:53:09 +0000, Richard Bos wrote:
Lawrence Kirby <lk****@netactive.co.uk> wrote:
2. You are setting up an object whick you might extend later using
realloc(). However whether malloc(0) return null or not is immaterial to
this, either result can be passed to realloc(). So the latitude given by
the standard is harmless here. Of course you have the issue of freeing the
"object" for a non-null return.


Even that is not a problem, since free(0) is harmless. No matter what
you get from malloc(), you can free() it.


True, my intent was more along the lines of you have consider calling free()
appropriately for a non-null return, whereas if the return was always
null in this case you wouldn't have to worry.

However given the possibility extending the object to non-zero length
there's likely to be code to handle freeing anyway, so it probably turns
out to be a non-issue.

Lawrence
Nov 14 '05 #9

P: n/a
Neo

"Ravi Uday" <ra******@gmail.com> wrote in message
news:1100686594.274808@sj-nntpcache-5...

"Neo" <ti***************@yahoo.com> wrote in message
news:30*************@uni-berlin.de...
Hi Folks,

I've a simple qestion related to dynamic memory allocation in C here is

the
code:

#include <stdio.h>

int main()

{

char *p;

if( (p=(char*)malloc(0)) == NULL)

printf("NULL\n");

else

printf("Valid Pointer\n");

return 0;

}

Output : "Valid Pointer"

Why this code fragment returns a valid pointer to a memory block???

-Neo

See what the standard says

4.10.3 Memory management functions:

If the size of the space requested is zero, the behavior is
*implementation-defined*; the value returned shall be either a null
pointer or a unique pointer.

So check in your impelementation documents for answer !

- Ravi


O'kay thanks for pointing it out.
But what should be the suggested behavior and why?
Is a valid pointer right way?
I think NULL is a better option? isn't it???

-Neo
Nov 14 '05 #10

P: n/a
Neo

"Lawrence Kirby" <lk****@netactive.co.uk> wrote in message
news:pa****************************@netactive.co.u k...
On Wed, 17 Nov 2004 15:49:10 +0530, Ravi Uday wrote:

"Neo" <ti***************@yahoo.com> wrote in message
news:30*************@uni-berlin.de...
Hi Folks,

I've a simple qestion related to dynamic memory allocation in C here is

the
code:

#include <stdio.h>

int main()

{

char *p;

if( (p=(char*)malloc(0)) == NULL)
Get rid of the cast. The compiler should then complain, which is
good because the code is broken. Adding the cast doesn't fix the
code, it just stops the compiler complaining about the problem.

The problem is that you don't have a valid declaration for malloc()
in scope when you call it. In that case the compiler assumes
that malloc() returns int, but it doesn't, it returns void *. All
standard library functions are provided with a declaration in
the appropriate standard header. For malloc() that is <stdlib.h>.

printf("NULL\n");

else

printf("Valid Pointer\n");

return 0;

}

Output : "Valid Pointer"

Why this code fragment returns a valid pointer to a memory block???
Your code invokes undefined behaviour due to the invalid cast, so anything
can happen. Once that's fixed the issue is as below i.e. the compiler does
it because the standard says it can.


invalid cast - what do you mean by saying *invalid cast*. isnt it a standard
practice to cast the pointer returned by the malloc() to desired type? or
how then it can be otherwise like:
p = malloc(0);
???

-Neo

See what the standard says

4.10.3 Memory management functions:

If the size of the space requested is zero, the behavior is
*implementation-defined*; the value returned shall be either a null
pointer or a unique pointer.

So check in your impelementation documents for answer !


Lawrence

Nov 14 '05 #11

P: n/a
Neo wrote:
I've a simple qestion related to dynamic memory allocation in C.
[snip]
cat main.c #include <stdio.h>
#include <stdlib.h>

int main(int argc, char* argv[]) {

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

if(NULL == p)
printf("NULL\n");
else
printf("Valid Pointer\n");

printf("*((int*)p - 1) = %d\n", *((int*)p - 1));
printf("p = %p\n", p);
return EXIT_SUCCESS;
}
gcc -Wall -std=c99 -pedantic -o main main.c
./main Valid Pointer
*((int*)p - 1) = 17
p = 0x9876008

My implementation allocates at least two
double word aligned double words
and returns a pointer to the second double word.
Why this code fragment returns a valid pointer to a memory block?


Because it can.

Nov 14 '05 #12

P: n/a
Neo wrote:
#include <stdio.h> if( (p=(char*)malloc(0)) == NULL)
isnt it a standard
practice to cast the pointer returned by the malloc() to desired type?


No.
It's a mistake that people make when they neglect to include stdlib.h,
and the compiler consequently warns them that malloc is returning
type int and needs to be cast.
Add
#include <stdlib.h>
and drop the cast.

--
pete
Nov 14 '05 #13

P: n/a

"Lawrence Kirby" <lk****@netactive.co.uk> wrote in message
news:pa****************************@netactive.co.u k...
On Wed, 17 Nov 2004 07:45:50 -0500, Method Man wrote:
...
<OT>

Why didn't they put it in the standard that a null pointer must be returned? It seems like the right/logical behaviour for calling malloc on size 0 and avoids any confusion.

</OT>


Probably because there were existing implementations for both types of
result. I don't think it makes much practical difference, I can only think
of 2 uses for this:

1. Creating a unique pointer value which compares unequal to all others.
For this to work you would need to prefer the non-null return behaviour.
Of course you can use malloc(1) for this. However malloc() can always fail
so it could return null for any call.


Fair enough. Although, I can't immediately see a practical use in obtaining
a valid pointer from malloc(0). I would be curious to know how the
implementation handled dereferencing and type-casting for this magical
pointer.
Nov 14 '05 #14

P: n/a
Neo
Right, thnx. for pointing it out.
its workin perfect!
-Neo

"pete" <pf*****@mindspring.com> wrote in message
news:41***********@mindspring.com...
Neo wrote:
>>> #include <stdio.h> >>> if( (p=(char*)malloc(0)) == NULL)

isnt it a standard
practice to cast the pointer returned by the malloc() to desired type?


No.
It's a mistake that people make when they neglect to include stdlib.h,
and the compiler consequently warns them that malloc is returning
type int and needs to be cast.
Add
#include <stdlib.h>
and drop the cast.

--
pete

Nov 14 '05 #15

P: n/a
Method Man <a@b.c> scribbled the following:
"Lawrence Kirby" <lk****@netactive.co.uk> wrote in message
news:pa****************************@netactive.co.u k...
On Wed, 17 Nov 2004 07:45:50 -0500, Method Man wrote:
> <OT>
>
> Why didn't they put it in the standard that a null pointer must be returned? > It seems like the right/logical behaviour for calling malloc on size 0 and > avoids any confusion.
>
> </OT>
Probably because there were existing implementations for both types of
result. I don't think it makes much practical difference, I can only think
of 2 uses for this:

1. Creating a unique pointer value which compares unequal to all others.
For this to work you would need to prefer the non-null return behaviour.
Of course you can use malloc(1) for this. However malloc() can always fail
so it could return null for any call.

Fair enough. Although, I can't immediately see a practical use in obtaining
a valid pointer from malloc(0). I would be curious to know how the
implementation handled dereferencing and type-casting for this magical
pointer.


If the C memory model was continuous rather than discrete, then there
would be no problem. In a continuous memory model, pointer values would
only serve as "starting points" of allocated memory, not allocated
memory itself. If you think of the conventional discrete memory model as
labelling boxes with addresses, in a continuous memory model you don't
label the boxes, you label the gaps between them. This way the malloc()
implementation could safely return the same, non-null, pointer value
over and over again from calls to malloc(0), because reserving 0 bytes
onward from that gap between boxes doesn't actually reserve any box at
all, and it's the boxes you store stuff in, not the gaps between them.
This is of course very much off-topic for comp.lang.c but those who
have studied real analysis and topology know what I'm talking about.

--
/-- Joona Palaste (pa*****@cc.helsinki.fi) ------------- Finland --------\
\-------------------------------------------------------- rules! --------/
"It's time, it's time, it's time to dump the slime!"
- Dr. Dante
Nov 14 '05 #16

P: n/a
In <5g******************@read1.cgocable.net> "Method Man" <a@b.c> writes:

"Lawrence Kirby" <lk****@netactive.co.uk> wrote in message
news:pa****************************@netactive.co. uk...
On Wed, 17 Nov 2004 07:45:50 -0500, Method Man wrote:
...
> <OT>
>
> Why didn't they put it in the standard that a null pointer must bereturned? > It seems like the right/logical behaviour for calling malloc on size 0and > avoids any confusion.
>
> </OT>
Probably because there were existing implementations for both types of
result. I don't think it makes much practical difference, I can only think
of 2 uses for this:

1. Creating a unique pointer value which compares unequal to all others.
For this to work you would need to prefer the non-null return behaviour.
Of course you can use malloc(1) for this. However malloc() can always fail
so it could return null for any call.


Fair enough. Although, I can't immediately see a practical use in obtaining
a valid pointer from malloc(0).


It's a "cheap" method for generating unique IDs.
I would be curious to know how the
implementation handled dereferencing and type-casting for this magical
pointer.


The pointer is as ordinary as you can get. Dereferencing it invokes
undefined behaviour and conversions work as for other pointers. As
Lawrence told you, if you need this particular behaviour, just use the
following wrapper for malloc:

void *xmalloc(size_t size)
{
if (size == 0) size = 1;
return malloc(size);
}

And if you need the other behaviour, you can trivially get it from:

void *ymalloc(size_t size)
{
if (size == 0) return NULL;
return malloc(size);
}

Or, if you prefer macros:

#define XMALLOC(size) malloc(size == 0 ? 1 : size)
#define YMALLOC(size) (size == 0 ? NULL : malloc(size))

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Currently looking for a job in the European Union
Nov 14 '05 #17

P: n/a

"Dan Pop" <Da*****@cern.ch> wrote in message
news:cn**********@sunnews.cern.ch...
In <5g******************@read1.cgocable.net> "Method Man" <a@b.c> writes:
Fair enough. Although, I can't immediately see a practical use in
obtaining
a valid pointer from malloc(0).


It's a "cheap" method for generating unique IDs.


Are successive calls to malloc(0) guaranteed to return unique values,
though? (Assuming they don't return NULL.) Given that actually
dereferencing such the pointer invokes undefined behaviour, couldn't a
malloc() implementation set aside a certain value that it always returns
when size is 0? It might have to increment a reference count that would
later get decremented by free().
Nov 14 '05 #18

P: n/a
"Craig Barkhouse" <ca******@student.cs.uwaterloo.ca> wrote:
Are successive calls to malloc(0) guaranteed to return unique values,
though? (Assuming they don't return NULL.) Given that actually
dereferencing such the pointer invokes undefined behaviour, couldn't a
malloc() implementation set aside a certain value that it always returns
when size is 0?


In C89, it isn't perfectly clear; the text says that

# 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; the value returned shall be either a null
# pointer or a unique pointer.

without clarifying whether that means a pointer unique to zero-sized
malloc()s, or a unique pointer for _each_ zero-sized malloc().

In C99, this has been changed to

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

Since

# Each such allocation shall yield a pointer to an object disjoint from
# any other object.

this means that in C99, each zero-sized malloc() must return a distinct
pointer (or a null pointer), and I think that with this knowledge, it's
clear that this was what was meant in C89, too.

Richard
Nov 14 '05 #19

P: n/a
"Method Man" <a@b.c> writes:
I can't immediately see a practical use in obtaining a valid
pointer from malloc(0). I would be curious to know how the
implementation handled dereferencing and type-casting for this
magical pointer.


Dereferencing the result of malloc(0) yields undefined behavior.
What problem do you envision with type-casting it?
--
"The way I see it, an intelligent person who disagrees with me is
probably the most important person I'll interact with on any given
day."
--Billy Chambless
Nov 14 '05 #20

P: n/a

"Ben Pfaff" <bl*@cs.stanford.edu> wrote in message
news:87************@benpfaff.org...
"Method Man" <a@b.c> writes:
I can't immediately see a practical use in obtaining a valid
pointer from malloc(0). I would be curious to know how the
implementation handled dereferencing and type-casting for this
magical pointer.
Dereferencing the result of malloc(0) yields undefined behavior.


How can you say for certain that it will yield UB? Assuming the pointer
obtained from malloc(0) is unique and valid, it therefore must be pointing
to some valid memory location. I thought only invalid and void pointers
caused UB when dereferenced. Perhaps I am misunderstanding something.
What problem do you envision with type-casting it?


I was brainstorming. I suppose there wouldn't be any problems.
Nov 14 '05 #21

P: n/a
"Neo" <ti***************@yahoo.com> wrote in message news:<30*************@uni-berlin.de>...
"Lawrence Kirby" <lk****@netactive.co.uk> wrote in message
news:pa****************************@netactive.co.u k...
On Wed, 17 Nov 2004 15:49:10 +0530, Ravi Uday wrote:
"Neo" <ti***************@yahoo.com> wrote in message
news:30*************@uni-berlin.de...

#include <stdio.h>

int main()
{
char *p;

if( (p=(char*)malloc(0)) == NULL)
Get rid of the cast. The compiler should then complain, which is
good because the code is broken. Adding the cast doesn't fix the
code, it just stops the compiler complaining about the problem.

The problem is that you don't have a valid declaration for malloc()
in scope when you call it. In that case the compiler assumes
that malloc() returns int, but it doesn't, it returns void *. All
standard library functions are provided with a declaration in
the appropriate standard header. For malloc() that is <stdlib.h>.
printf("NULL\n");
else
printf("Valid Pointer\n");

return 0;
}

Output : "Valid Pointer"

Why this code fragment returns a valid pointer to a memory block???


Your code invokes undefined behaviour due to the invalid cast, so anything
can happen. Once that's fixed the issue is as below i.e. the compiler does
it because the standard says it can.


invalid cast - what do you mean by saying *invalid cast*.


He means what he explained earlier. Here's another try:

Your code says that malloc() returns an int. Your cast has no well-
defined meaning, and prevents the compiler putting out an error
message that would have helped remind you that you hadn't included
the header file that declares malloc() properly.
isnt it a standard
practice to cast the pointer returned by the malloc() to desired type?
It's a common practice, and most knowledgeable C coders regard it
as a bad practice in all but a few special cases.
or how then it can be otherwise like:
p = malloc(0);
???


Yes. Does that surprise you? If you just take the cast out, you'll
get an error message. If you then include <stdlib.h> as you should
do when using malloc(), the error message will go away. The is because
the header file correctly declares malloc() to return a <void *>
which can be automatically converted to a <char *> by assignment.
Nov 14 '05 #22

P: n/a
On Thu, 18 Nov 2004 18:15:23 -0500, in comp.lang.c , "Method Man" <a@b.c>
wrote:

"Ben Pfaff" <bl*@cs.stanford.edu> wrote in message
news:87************@benpfaff.org...
"Method Man" <a@b.c> writes:
> I can't immediately see a practical use in obtaining a valid
> pointer from malloc(0). I would be curious to know how the
> implementation handled dereferencing and type-casting for this
> magical pointer.
Dereferencing the result of malloc(0) yields undefined behavior.


How can you say for certain that it will yield UB?


7.20.3 Memory management functions
"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."
So either you have as null pointer, or an unusable one.
Assuming the pointer obtained from malloc(0) is unique and valid,


it can't be - see above quote - except in the case where its a null
pointer, which is not dereferencable anyway.
--
Mark McIntyre
CLC FAQ <http://www.eskimo.com/~scs/C-faq/top.html>
CLC readme: <http://www.ungerhu.com/jxh/clc.welcome.txt>

----== Posted via Newsfeeds.Com - Unlimited-Uncensored-Secure Usenet News==----
http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups
----= East and West-Coast Server Farms - Total Privacy via Encryption =----
Nov 14 '05 #23

P: n/a
"Method Man" <a@b.c> writes:
"Ben Pfaff" <bl*@cs.stanford.edu> wrote in message
news:87************@benpfaff.org...
"Method Man" <a@b.c> writes:
> I can't immediately see a practical use in obtaining a valid
> pointer from malloc(0). I would be curious to know how the
> implementation handled dereferencing and type-casting for this
> magical pointer.
Dereferencing the result of malloc(0) yields undefined behavior.


How can you say for certain that it will yield UB?


Undefined behavior has to do with what the standard says. It
doesn't have to do with what happens in real life. In this case,
the standard says "the returned pointer shall not be used to
access an object," so an attempt to dereference it yields
undefined behavior.
Assuming the pointer obtained from malloc(0) is unique and
valid, it therefore must be pointing to some valid memory
location. I thought only invalid and void pointers caused UB
when dereferenced. Perhaps I am misunderstanding something.


You can't dereference a void pointer. You have to convert it to
a pointer to some complete type first.
--
int main(void){char p[]="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuv wxyz.\
\n",*q="kl BIcNBFr.NKEzjwCIxNJC";int i=sizeof p/2;char *strchr();int putchar(\
);while(*q){i+=strchr(p,*q++)-p;if(i>=(int)sizeof p)i-=sizeof p-1;putchar(p[i]\
);}return 0;}
Nov 14 '05 #24

P: n/a
Method Man wrote:

"Ben Pfaff" <bl*@cs.stanford.edu> wrote in message
news:87************@benpfaff.org...

Dereferencing the result of malloc(0) yields undefined behavior.


How can you say for certain that it will yield UB?

Because the standard says the returned pointer shall not be used to
access an object.


Brian
Nov 14 '05 #25

P: n/a

"Default User" <fi********@boeing.com.invalid> wrote in message
news:I7********@news.boeing.com...
Method Man wrote:

"Ben Pfaff" <bl*@cs.stanford.edu> wrote in message
news:87************@benpfaff.org...

Dereferencing the result of malloc(0) yields undefined behavior.


How can you say for certain that it will yield UB?

Because the standard says the returned pointer shall not be used to
access an object.


Ok, thanks. I must have missed reading that.
Nov 14 '05 #26

P: n/a
"Craig Barkhouse" <ca******@student.cs.uwaterloo.ca> writes:
"Dan Pop" <Da*****@cern.ch> wrote in message
news:cn**********@sunnews.cern.ch...
In <5g******************@read1.cgocable.net> "Method Man" <a@b.c> writes:
Fair enough. Although, I can't immediately see a practical use in
obtaining
a valid pointer from malloc(0).


It's a "cheap" method for generating unique IDs.


Are successive calls to malloc(0) guaranteed to return unique values,
though? (Assuming they don't return NULL.) Given that actually
dereferencing such the pointer invokes undefined behaviour, couldn't a
malloc() implementation set aside a certain value that it always returns
when size is 0? It might have to increment a reference count that would
later get decremented by free().


Yes, I believe it has to be unique. The wording in the standard is:

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.

Since the behavior if the size is nonzero is to return a unique
pointer (ignoring recycling of free()d pointers), each call to
malloc(0) has to return a unique pointer (if it doesn't return a null
pointer).

--
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 #27

P: n/a
Da*****@cern.ch (Dan Pop) writes:
[...]
Or, if you prefer macros:

#define XMALLOC(size) malloc(size == 0 ? 1 : size)
#define YMALLOC(size) (size == 0 ? NULL : malloc(size))


Your XMALLOC is probably clearer than the one I came up with, but I'm
going to show it off because I think it's kinda clever.

#define XMALLOC(size) malloc((size) + ((size)==0))

(Yes, I habitually parenthesize references to arguments to
function-like macros; it's easier than figuring out when it isn't
necessary.)

--
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 #28

P: n/a
"Keith Thompson" <ks***@mib.org> wrote in message
news:ln************@nuthaus.mib.org...
"Craig Barkhouse" <ca******@student.cs.uwaterloo.ca> writes:
"Dan Pop" <Da*****@cern.ch> wrote in message
news:cn**********@sunnews.cern.ch...
In <5g******************@read1.cgocable.net> "Method Man" <a@b.c> writes:
Fair enough. Although, I can't immediately see a practical use in
obtaining
a valid pointer from malloc(0).

It's a "cheap" method for generating unique IDs.


Are successive calls to malloc(0) guaranteed to return unique values,
though? (Assuming they don't return NULL.) Given that actually
dereferencing such the pointer invokes undefined behaviour, couldn't a
malloc() implementation set aside a certain value that it always returns
when size is 0? It might have to increment a reference count that would
later get decremented by free().


Yes, I believe it has to be unique. The wording in the standard is:

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.

Since the behavior if the size is nonzero is to return a unique
pointer (ignoring recycling of free()d pointers), each call to
malloc(0) has to return a unique pointer (if it doesn't return a null
pointer).


This is perfectly acceptable behavior. There are architectures
that have unusable memory ranges within the total possible range
that could be represented by a (void*). A conforming implementation
could choose an available unique value from the unusable range to
return from malloc()/calloc() when the requested size is zero. A
later free() would accept that unusable pointer.

Although I think it would be simpler to just return null, rather
than keeping track of the "unusable" pointers returned by malloc(0)
for later free().

Even better would be for the programmer to verify that his
processing doesn't request zero bytes nor attempt to free
a null pointer value, but that's just how I like to program...eek!
Nov 14 '05 #29

P: n/a
"xarax" <xa***@email.com> writes:
"Keith Thompson" <ks***@mib.org> wrote in message

[...]
Since the behavior if the size is nonzero is to return a unique
pointer (ignoring recycling of free()d pointers), each call to
malloc(0) has to return a unique pointer (if it doesn't return a null
pointer).


This is perfectly acceptable behavior. There are architectures
that have unusable memory ranges within the total possible range
that could be represented by a (void*). A conforming implementation
could choose an available unique value from the unusable range to
return from malloc()/calloc() when the requested size is zero. A
later free() would accept that unusable pointer.


The simplest way for malloc() to return a unique pointer for each
malloc(0) would be for it to change the argument internally to 1:

void *malloc(size_t size)
{
if (size == 0) size = 1;
/* the rest of the function */
}

Even this isn't necessary if the uniqueness is a natural consequence
of the algorithm (i.e., 0 might not have to be treated as a special
case).

--
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 #30

P: n/a


Keith Thompson wrote:

This is perfectly acceptable behavior. There are architectures
that have unusable memory ranges within the total possible range
that could be represented by a (void*). A conforming implementation
could choose an available unique value from the unusable range to
return from malloc()/calloc() when the requested size is zero. A
later free() would accept that unusable pointer.

The simplest way for malloc() to return a unique pointer for each
malloc(0) would be for it to change the argument internally to 1:

void *malloc(size_t size)
{
if (size == 0) size = 1;
/* the rest of the function */
}


There's no guarantee that this will return a unique pointer.
Even a malloc of size 1 may fail if the memory resources are
exhausted.
--
Al Bowers
Tampa, Fl USA
mailto: xa******@myrapidsys.com (remove the x to send email)
http://www.geocities.com/abowers822/

Nov 14 '05 #31

P: n/a
Al Bowers <xa******@rapidsys.com> writes:
Keith Thompson wrote:

This is perfectly acceptable behavior. There are architectures
that have unusable memory ranges within the total possible range
that could be represented by a (void*). A conforming implementation
could choose an available unique value from the unusable range to
return from malloc()/calloc() when the requested size is zero. A
later free() would accept that unusable pointer.

The simplest way for malloc() to return a unique pointer for each
malloc(0) would be for it to change the argument internally to 1:
void *malloc(size_t size)
{
if (size == 0) size = 1;
/* the rest of the function */
}


There's no guarantee that this will return a unique pointer.
Even a malloc of size 1 may fail if the memory resources are
exhausted.


Which, again, is perfectly acceptable. If the implementation decides
to have malloc(0) return a unique pointer on each call, it can't do so
indefinitely; eventually it will fail by running out of memory, and it
will indicate the failure by returning a null pointer.

The standard (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.

Making malloc(0) equivalent to malloc(1) satisfies this.

--
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 #32

P: n/a
In <82*****************@read1.cgocable.net> "Method Man" <a@b.c> writes:

"Ben Pfaff" <bl*@cs.stanford.edu> wrote in message
news:87************@benpfaff.org...
"Method Man" <a@b.c> writes:
> I can't immediately see a practical use in obtaining a valid
> pointer from malloc(0). I would be curious to know how the
> implementation handled dereferencing and type-casting for this
> magical pointer.
Dereferencing the result of malloc(0) yields undefined behavior.


How can you say for certain that it will yield UB? Assuming the pointer
obtained from malloc(0) is unique and valid, it therefore must be pointing
to some valid memory location.


It's the same as with pointers pointing one past the last element of an
array. They're "valid" only in the sense that assigning, converting or
comparing them for equality works normally, but they cannot be
dereferenced. Whether they point to a valid memory location is up to
the implementor (have a look at Electric Fence to see how an
implementation can create invalid memory locations having valid memory
addresses).
I thought only invalid and void pointers
caused UB when dereferenced. Perhaps I am misunderstanding something.


If the standard says that a pointer value cannot be used to access an
object, attempting to do so results in undefined behaviour. This is
different from an invalid pointer value, which cannot be used at all
without invoking undefined behaviour (except for examining its
representation on a byte by byte basis).

E.g.

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

At this point, assuming that both malloc calls returned non-null pointers,
p contains a valid pointer value that cannot be dereferenced, while q
contains an invalid pointer value, which cannot be used at all without
invoking undefined behaviour.

Void pointers are in a different category: the attempt to dereference
them is a constraint violation, so a diagnostic is required.

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Currently looking for a job in the European Union
Nov 14 '05 #33

P: n/a


Keith Thompson wrote:
Al Bowers <xa******@rapidsys.com> writes:
Keith Thompson wrote:

The simplest way for malloc() to return a unique pointer for each
malloc(0) would be for it to change the argument internally to 1:
void *malloc(size_t size)
{
if (size == 0) size = 1;
/* the rest of the function */
}


There's no guarantee that this will return a unique pointer.
Even a malloc of size 1 may fail if the memory resources are
exhausted.

Which, again, is perfectly acceptable. If the implementation decides
to have malloc(0) return a unique pointer on each call, it can't do so
indefinitely; eventually it will fail by running out of memory, and it
will indicate the failure by returning a null pointer.

The standard (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.

Making malloc(0) equivalent to malloc(1) satisfies this.


Yes, your internal implement satisfies the Standard requirements. Either
a NULL value is returned or a unique pointer value. Your implement
is weighed to the latter.

I was just questioning the wording in your description.
Specifically in the comment:

"The simplest way for malloc() to return a unique pointer for each
malloc(0) would be for it to change the argument internally to 1"

I was equating your word "each" to mean "all".

At some point the implement may be unable to return
a unique pointer(it returns NULL), which means that one cannot
say that every call to malloc(0) will return a unique pointer.

--
Al Bowers
Tampa, Fl USA
mailto: xa******@myrapidsys.com (remove the x to send email)
http://www.geocities.com/abowers822/

Nov 14 '05 #34

P: n/a
Al Bowers <xa******@rapidsys.com> writes:
[...]
Yes, your internal implement satisfies the Standard requirements. Either
a NULL value is returned or a unique pointer value. Your implement
is weighed to the latter.

I was just questioning the wording in your description.
Specifically in the comment:

"The simplest way for malloc() to return a unique pointer for each
malloc(0) would be for it to change the argument internally to 1"


You're right, I should have qualified that.

--
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 #35

P: n/a
On 18 Nov 2004 15:06:02 GMT
Joona I Palaste <pa*****@cc.helsinki.fi> wrote:
Method Man <a@b.c> scribbled the following:
<snip>
Fair enough. Although, I can't immediately see a practical use in
obtaining a valid pointer from malloc(0). I would be curious to know
how the implementation handled dereferencing and type-casting for
this magical pointer.


If the C memory model was continuous rather than discrete, then there
would be no problem. In a continuous memory model, pointer values
would only serve as "starting points" of allocated memory, not
allocated memory itself. If you think of the conventional discrete
memory model as labelling boxes with addresses, in a continuous memory
model you don't label the boxes, you label the gaps between them. This
way the malloc() implementation could safely return the same,
non-null, pointer value over and over again from calls to malloc(0),


I don't think this would be allowed. I think that any valid pointer (as
opposed to null pointer) returned by malloc must compare different to
any other object that still exists. I.e.

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
void *p1 = malloc(0);
void *p2 = malloc(0);

if (p1 && (p1 == p2))
puts("This should never be printed!");

return 0;
}

Modulo any errors people point out (I've not tried it) I don't believe
the above is allowed to print "This should never be printed!" which it
would with the implementation you describe.
because reserving 0 bytes onward from that gap between boxes doesn't
actually reserve any box at all, and it's the boxes you store stuff
in, not the gaps between them. This is of course very much off-topic
for comp.lang.c but those who have studied real analysis and topology
know what I'm talking about.


I know what you are talking about, I just don't think it is allowed.

One possible way the library could implement malloc(0) returning a
non-null pointer is to treat it as malloc(1), I.e. give you a pointer
to a byte that it really has allocated. After all, a derefference isn't
guaranteed to fail by the standard.
--
Flash Gordon
Living in interesting times.
Although my email address says spam, it is real and I read it.
Nov 14 '05 #36

P: n/a
On Thu, 18 Nov 2004 08:49:38 +0530
"Neo" <ti***************@yahoo.com> wrote:

<snip not casting the return value of malloc.
invalid cast - what do you mean by saying *invalid cast*. isnt it a
standard practice to cast the pointer returned by the malloc() to
desired type? or how then it can be otherwise like:
p = malloc(0);
???


In C it is standard practice to not cast the value returned by malloc.
There are a few obscure exceptions, an one person who posts here has a
good reason why he (as opposed to everyone else) has to.

If you use a function without a prototype the compiler assumes it
returns an int where as malloc actually returns void*. Thus if, for
example, pointers are returned in A0 (an address register) and ints are
returned in D0 (a data register) then the compiled version of your code
will ignore the pointer returned by malloc and instead convert some
random value that happens to be in D0 to a pointer, this is obviously
likely to cause your program to fail, probably when your boss is
demonstrating the program to a very big potential customer. Such is the
rath of invoking undefined behaviour.

If you don't have the cast and you have forgotten to include stdlib.h
then the compiler is *required* to generating a diagnostic (C99 is
different and a diagnostic is required even with the cast, but I'll bet
you are not using a*conforming* C99 implementation).

Conversion between void* and other object (not function) pointers is
automatic and does not require a cast.

The prefered (by most of the regulars) method of calling malloc around
here is
p = malloc( n * sizeof *p);

If you search the group you can find lots of discussion on this point.
--
Flash Gordon
Living in interesting times.
Although my email address says spam, it is real and I read it.
Nov 14 '05 #37

P: n/a
On Fri, 19 Nov 2004 01:11:17 GMT
Keith Thompson <ks***@mib.org> wrote:
Da*****@cern.ch (Dan Pop) writes:
[...]
Or, if you prefer macros:

#define XMALLOC(size) malloc(size == 0 ? 1 : size)
#define YMALLOC(size) (size == 0 ? NULL : malloc(size))


Your XMALLOC is probably clearer than the one I came up with, but I'm
going to show it off because I think it's kinda clever.

#define XMALLOC(size) malloc((size) + ((size)==0))

(Yes, I habitually parenthesize references to arguments to
function-like macros; it's easier than figuring out when it isn't
necessary.)


Of course, either macro is a potential problem if you do
p = XMALLOC( size_array[i++] );
--
Flash Gordon
Living in interesting times.
Although my email address says spam, it is real and I read it.
Nov 14 '05 #38

P: n/a
Flash Gordon wrote:

Neo wrote:

<snip not casting the return value of malloc.

invalid cast - what do you mean by saying *invalid cast*. isnt it a
standard practice to cast the pointer returned by the malloc() to
desired type? or how then it can be otherwise like:
p = malloc(0);
???
In C, it is standard practice to not cast the value returned by malloc.
Nonsense!
There are a few obscure exceptions, and one person who posts here
has a good reason why he (as opposed to everyone else) has to.
Lots of people who post here have good rerasons
to cast the pointer returned by the malloc(size_t).
If you use a function without a prototype
Don't do that.
the compiler assumes [that] it returns an int
where as malloc actually returns void*.
Thus if, for example, pointers are returned in A0 (an address register)
and ints are returned in D0 (a data register),
then the compiled version of your code
will ignore the pointer returned by malloc and instead
convert some random value that happens to be in D0 to a pointer,
this is obviously likely to cause your program to fail,
probably when your boss is demonstrating the program
to a very big potential customer.
Such is the rath of invoking undefined behaviour.
FUD

http://en.wikipedia.org/wiki/FUD
If you don't have the cast and you have forgotten to include stdlib.h
then the compiler is *required* to generating a diagnostic
(C99 is different and a diagnostic is required even with the cast,
but I'll bet you are not using a *conforming* C99 implementation).
Then you should get a C compiler that conforms with this requirement.
There are plenty of them them that do.
Conversion between void* and other object (not function) pointers
is [implicit and] automatic and does not require a cast.

The prefered (by most of the regulars) method
of calling malloc around here is

p = malloc( n * sizeof *p);


This is a matter of style and [poor] taste.

Write:

char* p = (char*)malloc(n*sizeof(char*));

and both C and C++ compilers will accept your code.

Nov 14 '05 #39

P: n/a
On Fri, 19 Nov 2004 15:26:05 -0800
"E. Robert Tisdale" <E.**************@jpl.nasa.gov> wrote:
Flash Gordon wrote:
Neo wrote:

<snip not casting the return value of malloc.

invalid cast - what do you mean by saying *invalid cast*. isnt it a
standard practice to cast the pointer returned by the malloc() to
desired type? or how then it can be otherwise like:
p = malloc(0);
???
In C, it is standard practice to not cast the value returned by
malloc.


Nonsense!
There are a few obscure exceptions, and one person who posts here
has a good reason why he (as opposed to everyone else) has to.


Lots of people who post here have good rerasons
to cast the pointer returned by the malloc(size_t).
If you use a function without a prototype


Don't do that.


Agreed. I even explain below why not.
the compiler assumes [that] it returns an int
where as malloc actually returns void*.
Thus if, for example, pointers are returned in A0 (an address
register) and ints are returned in D0 (a data register),
then the compiled version of your code
will ignore the pointer returned by malloc and instead
convert some random value that happens to be in D0 to a pointer,
this is obviously likely to cause your program to fail,
probably when your boss is demonstrating the program
to a very big potential customer.
Such is the rath of invoking undefined behaviour.


FUD

http://en.wikipedia.org/wiki/FUD


It is entirely real. I've used a 68000 based system that returned
pointers in A0 and ints in D0. Also as you should be aware we are
getting new systems where int and pointers are not the same size,
leading to more systems where it would fail.
If you don't have the cast and you have forgotten to include
stdlib.h then the compiler is *required* to generating a diagnostic
(C99 is different and a diagnostic is required even with the cast,
but I'll bet you are not using a *conforming* C99 implementation).


Then you should get a C compiler that conforms with this requirement.
There are plenty of them them that do.


Name 5 conforming C99 implementations. I'll start you off with gcc not
being one, since GNU explicitly states that it does not yet conform.
Conversion between void* and other object (not function) pointers
is [implicit and] automatic and does not require a cast.

The prefered (by most of the regulars) method
of calling malloc around here is

p = malloc( n * sizeof *p);


This is a matter of style and [poor] taste.

Write:

char* p = (char*)malloc(n*sizeof(char*));

and both C and C++ compilers will accept your code.


As discussed previously, with very few exceptions there is no good
reason to nead to compile C code as C++, especially since there are
various things which compile and behave differently.

You are, of course, trolling, I only respond so that newbies don't think
I accept your claims. Unless you can name 5 conforming C99
implementations (which should be easy if your claim that there are
plenty were true) then consider any lack of responce to further posts by
you to indicate that I disagree with you.
--
Flash Gordon
Living in interesting times.
Although my email address says spam, it is real and I read it.
Nov 14 '05 #40

P: n/a
"E. Robert Tisdale" <E.**************@jpl.nasa.gov> writes:
Flash Gordon wrote:
Neo wrote:
<snip not casting the return value of malloc.
invalid cast - what do you mean by saying *invalid cast*. isnt it a
standard practice to cast the pointer returned by the malloc() to
desired type? or how then it can be otherwise like:
p = malloc(0);
???
In C, it is standard practice to not cast the value returned by malloc.
Nonsense!


No, it's not nonsense, as we've repeatedly explained at length.
There are a few obscure exceptions, and one person who posts here
has a good reason why he (as opposed to everyone else) has to.


Lots of people who post here have good rerasons
to cast the pointer returned by the malloc(size_t).


You claim to have a good reason, with no real justification that I've
seen. P.J. Plauger apparently does have a good reason; he needs to
write code that his customers can compile either as C or as C++. I
haven't seen anyone else make a coherent argument in favor of casting
the result of malloc().

[...]
Write:

char* p = (char*)malloc(n*sizeof(char*));

and both C and C++ compilers will accept your code.


Write

char *p = malloc(n);

or

some_type *p = malloc(n * sizeof *p);

and use a C compiler. Or use a "new" operator and use a C++ compiler.

--
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 #41

P: n/a
On Fri, 19 Nov 2004 23:26:05 UTC, "E. Robert Tisdale"
<E.**************@jpl.nasa.gov> wrote:
Write:

char* p = (char*)malloc(n*sizeof(char*));

and both C and C++ compilers will accept your code.


Twitsdale is posting crap once again. Twitsdale is unable to learn C
as defined by the standard because he thinks ther is no other C
compiler as Wincrap existent on the real world.

Put twitsdale into your filters and you bewares yourself always of the
crap this bloody ignorant craps out of his ass.

There is really NO, absolutely NO reason to cast the result of a
function that returns a pointer to void. But here are thousend reasons
you invoke the lands of undefined behvior. When you writs C++ you have
in no ways a reason to use malloc() - new will always be better. When
you have to write C - use a C-compiler, when you have to write C++
then you have to use a C++-comiler.

--
Tschau/Bye
Herbert

Visit http://www.ecomstation.de the home of german eComStation

Nov 14 '05 #42

P: n/a
On Thu, 18 Nov 2004 18:25:05 UTC, Ben Pfaff <bl*@cs.stanford.edu>
wrote:
"Method Man" <a@b.c> writes:
I can't immediately see a practical use in obtaining a valid
pointer from malloc(0). I would be curious to know how the
implementation handled dereferencing and type-casting for this
magical pointer.
Dereferencing the result of malloc(0) yields undefined behavior.


No, implementation defined behavior only.
What problem do you envision with type-casting it?


undefined behavior as always by casting a result of a function that
returns pointer to void and is called without prototype in sight.
Implemenation defined behavior can be tolerable - undefined behavior
is never.

--
Tschau/Bye
Herbert

Visit http://www.ecomstation.de the home of german eComStation

Nov 14 '05 #43

P: n/a
"Herbert Rosenau" <os****@pc-rosenau.de> writes:
On Thu, 18 Nov 2004 18:25:05 UTC, Ben Pfaff <bl*@cs.stanford.edu>
wrote:
"Method Man" <a@b.c> writes:
> I can't immediately see a practical use in obtaining a valid
> pointer from malloc(0). I would be curious to know how the
> implementation handled dereferencing and type-casting for this
> magical pointer.
Dereferencing the result of malloc(0) yields undefined behavior.


No, implementation defined behavior only.


Here is what the standard says:

If an invalid value has been assigned to the pointer, the
behavior of the unary * operator is undefined.83)

If malloc(0) returns a null pointer, then this is sufficient to
makes its behavior undefined. If malloc(0) return a non-null
pointer, then this quote from the standard holds:

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.

A violation of a "shall" requirement yields undefined behavior:

If a ``shall'' or ``shall not'' requirement that appears
outside of a constraint is violated, the behavior is
undefined.

Why do you think that dereferencing malloc(0) yields only
implementation-defined behavior?
What problem do you envision with type-casting it?


undefined behavior as always by casting a result of a function that
returns pointer to void and is called without prototype in sight.


I don't see how this is specific to malloc(0), and I don't see
that this is the issue at hand anyhow.
Implemenation defined behavior can be tolerable - undefined
behavior is never.


Only in programs intended to be completely portable.
--
"What is appropriate for the master is not appropriate for the novice.
You must understand the Tao before transcending structure."
--The Tao of Programming
Nov 14 '05 #44

P: n/a
Herbert Rosenau <os****@pc-rosenau.de> scribbled the following:
On Fri, 19 Nov 2004 23:26:05 UTC, "E. Robert Tisdale"
<E.**************@jpl.nasa.gov> wrote:
Write:

char* p = (char*)malloc(n*sizeof(char*));

and both C and C++ compilers will accept your code.

Twitsdale is posting crap once again. Twitsdale is unable to learn C
as defined by the standard because he thinks ther is no other C
compiler as Wincrap existent on the real world. Put twitsdale into your filters and you bewares yourself always of the
crap this bloody ignorant craps out of his ass. There is really NO, absolutely NO reason to cast the result of a
function that returns a pointer to void. But here are thousend reasons
you invoke the lands of undefined behvior. When you writs C++ you have
in no ways a reason to use malloc() - new will always be better. When
you have to write C - use a C-compiler, when you have to write C++
then you have to use a C++-comiler.


Furthermore, Trollsdale used the wrong type in his sizeof operation.
The correct type would be what the pointer points at, not the pointer
type itself. sizeof *p would have worked much better.

--
/-- Joona Palaste (pa*****@cc.helsinki.fi) ------------- Finland --------\
\-------------------------------------------------------- rules! --------/
"Normal is what everyone else is, and you're not."
- Dr. Tolian Soran
Nov 14 '05 #45

P: n/a
Hello,

Herbert Rosenau <os****@pc-rosenau.de> schrieb:
When you writs C++ you have in no ways a reason to use malloc() - new
will always be better.


If I want to implement my own operator new, there are legit reasons to
call malloc on my own, even in C++.

But this is getting OT in this newsgroup here.

Regards,
Spiro.

--
Spiro R. Trikaliotis
http://www.trikaliotis.net/
http://www.viceteam.org/
Nov 14 '05 #46

P: n/a
On Sat, 20 Nov 2004 23:26:21 +0000 (UTC), in comp.lang.c , "Herbert
Rosenau" <os****@pc-rosenau.de> wrote:
On Thu, 18 Nov 2004 18:25:05 UTC, Ben Pfaff <bl*@cs.stanford.edu>
wrote:
"Method Man" <a@b.c> writes:
> I can't immediately see a practical use in obtaining a valid
> pointer from malloc(0). I would be curious to know how the
> implementation handled dereferencing and type-casting for this
> magical pointer.


Dereferencing the result of malloc(0) yields undefined behavior.


No, implementation defined behavior only.


The return from malloc is implementation defined but must be either a null
pointer or an unusable pointer. Dereferencing either of those is undefined,
by definition....
--
Mark McIntyre
CLC FAQ <http://www.eskimo.com/~scs/C-faq/top.html>
CLC readme: <http://www.ungerhu.com/jxh/clc.welcome.txt>

----== Posted via Newsfeeds.Com - Unlimited-Uncensored-Secure Usenet News==----
http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups
----= East and West-Coast Server Farms - Total Privacy via Encryption =----
Nov 14 '05 #47

P: n/a
On Sun, 21 Nov 2004 11:46:27 +0100, in comp.lang.c , Spiro Trikaliotis
<ne*********@trikaliotis.net> wrote:
Hello,

Herbert Rosenau <os****@pc-rosenau.de> schrieb:
When you writs C++ you have in no ways a reason to use malloc() - new
will always be better.
If I want to implement my own operator new,


But this isn't writing in C++, this is writing a compiler... :-)
there are legit reasons to
call malloc on my own, even in C++.
If you want to implement your own operator new, you'd be better advised to
use processor-specific memory management primitives.
But this is getting OT in this newsgroup here.


indeed.
--
Mark McIntyre
CLC FAQ <http://www.eskimo.com/~scs/C-faq/top.html>
CLC readme: <http://www.ungerhu.com/jxh/clc.welcome.txt>

----== Posted via Newsfeeds.Com - Unlimited-Uncensored-Secure Usenet News==----
http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups
----= East and West-Coast Server Farms - Total Privacy via Encryption =----
Nov 14 '05 #48

P: n/a
"E. Robert Tisdale" <E.**************@jpl.nasa.gov> wrote in message
news:cn**********@nntp1.jpl.nasa.gov...
Write:

char* p = (char*)malloc(n*sizeof(char*));

and both C and C++ compilers will accept your code.


Right : neither will catch that you don't get the difference between char and
char* !

A compromise solution :

#define MALLOC(count, type) ((type *)malloc((count) * sizeof(type)))

and use it without a cast :

char *p = MALLOC(n, char);

that will work in both C and C++, and enforce consistency between allocation and
use.

Of course a compiler that does not complain about calling a function without
proper prototype is either broken or misconfigured. Fix that first.

Chqrlie.
Nov 14 '05 #49

P: n/a
In <92************@brenda.flash-gordon.me.uk> Flash Gordon <sp**@flash-gordon.me.uk> writes:
On Fri, 19 Nov 2004 01:11:17 GMT
Keith Thompson <ks***@mib.org> wrote:
Da*****@cern.ch (Dan Pop) writes:
[...]
> Or, if you prefer macros:
>
> #define XMALLOC(size) malloc(size == 0 ? 1 : size)
> #define YMALLOC(size) (size == 0 ? NULL : malloc(size))


Your XMALLOC is probably clearer than the one I came up with, but I'm
going to show it off because I think it's kinda clever.

#define XMALLOC(size) malloc((size) + ((size)==0))

(Yes, I habitually parenthesize references to arguments to
function-like macros; it's easier than figuring out when it isn't
necessary.)


Of course, either macro is a potential problem if you do
p = XMALLOC( size_array[i++] );


The names are spelled in upper case to warn the user that they're macros,
not functions. If the user chooses to ignore the warnings, he gets
exactly what he deserves.

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Currently looking for a job in the European Union
Nov 14 '05 #50

54 Replies

This discussion thread is closed

Replies have been disabled for this discussion.