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 54 7761
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
"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
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
"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>
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
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
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
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
"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
"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
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.
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
"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.
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
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
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
"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().
"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
"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
"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.
"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.
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 =----
"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;}
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
"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.
"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. 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.
"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!
"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.
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/
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.
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
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/
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.
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.
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.
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.
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.
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.
"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.
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
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
"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
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
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/
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 =----
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 =----
"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.
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 This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics
by: mike79 |
last post by:
hi all..
if I wanted to malloc a struct, say the following:
struct myStruct1
{
int number;
char *string;
}
|
by: pembed2003 |
last post by:
Hi,
If I have the folllowing:
char* p = malloc(5);
memset(p,-1,5);
*p = 0;
printf("%d\n",strlen(p));
free(p);
It will print 0. Is there a way to retrive the initial size of memory
|
by: Rano |
last post by:
/*
Hello,
I've got some troubles with a stupid program...
In fact, I just start with the C language and sometime
I don't understand how I really have to use malloc.
I've readden the FAQ...
|
by: Joris Adriaenssens |
last post by:
This is my first posting, please excuse me if it is off-topic.
I'm learning to program in C. It's been almost ten years I've been
programming and a lot of things have changed apparently.
I...
|
by: Marlene Stebbins |
last post by:
At one point in my program I have about a dozen calls to malloc. I want
to check for malloc failure, but I don't want to write:
if((buffer_x = malloc(BUFSIZE * sizeof(*buffer_x))) == NULL)
{...
|
by: Zheng Da |
last post by:
Program received signal SIGSEGV, Segmentation fault.
0x40093343 in _int_malloc () from /lib/tls/libc.so.6
(gdb) bt
#0 0x40093343 in _int_malloc () from /lib/tls/libc.so.6
#1 0x40094c54 in malloc...
|
by: cs |
last post by:
This is the function malloc_m() that should be like malloc() but it
should find memory leak, and over bound writing in arrays.
How many errors do you see?
Thank you...
|
by: melanieab |
last post by:
Hi,
I'm having trouble when I leave a tabpage to go on to the next. On Focus
Leave, I take a snapshot of that tab. It usually turns out ok, but often,
part of the next tabpage will appear in...
|
by: desktop |
last post by:
I have read in Bjarne Stroustrup that using malloc and free should be
avoided in C++ because they deal with uninitialized memory and one
should instead use new and delete.
But why is that a...
|
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...
|
by: ryjfgjl |
last post by:
ExcelToDatabase: batch import excel into database automatically...
|
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...
|
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...
|
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...
|
by: ArrayDB |
last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
|
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
|
by: Faith0G |
last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
|
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...
| |