473,396 Members | 2,068 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

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

malloc size

Hi,

Inside a program how do i find out what size has been allocated to
pointer using malloc. eg...

int *p;
p=(int*)malloc(1024*sizeof(int));
now how do find how much has been allocated to p?

mojozoox!

Nov 14 '05 #1
40 3867
ma*******@HotPop.com wrote:
Inside a program how do i find out what size has been allocated to
pointer using malloc. eg...
int *p=(int*)malloc(1024*sizeof(int));
now how do find how much has been allocated to p?


If malloc succeeds, the result will have the size you asked for (in this
case, 1024*sizeof(int)). If you're passing pointers around and don't
know how much was malloc'ed, you simply have to track that information
yourself along with the pointer. This may seem silly, since the
underlying memory allocation system almost always needs to track this
information itself, but there are conceivably allocation systems that
would keep it only implicitly and make it hard to obtain.
--
Derrick Coetzee
I grant this newsgroup posting into the public domain. I disclaim all
express or implied warranty and all liability. I am not a professional.
Nov 14 '05 #2
Hi

AFAIK, its not possible to find the size of array allocated by malloc.
You provide this value to malloc...so, you are the one who has to keep
track of it.
usually, a constant say "#define ARRAYSIZE 1024" is used and this
constant is used in malloc and anywhere else the array size needs to be
found

HTH
Anitha

ma*******@HotPop.com wrote:
Hi,

Inside a program how do i find out what size has been allocated to
pointer using malloc. eg...

int *p;
p=(int*)malloc(1024*sizeof(int));
now how do find how much has been allocated to p?

mojozoox!


Nov 14 '05 #3
On 5 Jan 2005 19:29:18 -0800, ma*******@HotPop.com wrote:
Hi,

Inside a program how do i find out what size has been allocated to
pointer using malloc. eg...

int *p;
p=(int*)malloc(1024*sizeof(int));
now how do find how much has been allocated to p?

If you don't keep track of it yourself, there is no portable way.
<<Remove the del for email>>
Nov 14 '05 #4
ma*******@HotPop.com wrote:
How do I find out inside a program
what size has been allocated to pointer using malloc. e.g.:

int *p=(int*)malloc(1024*sizeof(int));

Now how do find how much has been allocated to p?
It's implementation dependent.
cat main.c #include <stdio.h>
#include <stdlib.h>

size_t allocation(const void* p) {
return ((size_t*)p)[-1] - 1;
}

int main(int argc, char* argv[]) {
if (1 < argc) {
const size_t n = atoi(argv[1]);
const void* p = malloc(n);
fprintf(stdout, "size = %u\n", allocation(p));
free((void*)p);
}
return EXIT_SUCCESS;
}
gcc -Wall -std=c99 -pedantic -o main main.c
./main 1

size = 16
Nov 14 '05 #5
Hi

AFAIK, its not possible to find the size of array allocated by malloc.
You provide this value to malloc...so, you are the one who has to keep
track of it.
usually, a constant say "#define ARRAYSIZE 1024" is used and this
constant is used in malloc and anywhere else the array size needs to be
found

HTH
Anitha

ma*******@HotPop.com wrote:
Hi,

Inside a program how do i find out what size has been allocated to
pointer using malloc. eg...

int *p;
p=(int*)malloc(1024*sizeof(int));
now how do find how much has been allocated to p?

mojozoox!


Nov 14 '05 #6

<ma*******@HotPop.com> wrote in message
news:11**********************@f14g2000cwb.googlegr oups.com...
Hi,

Inside a program how do i find out what size has been allocated to
pointer using malloc. eg...

int *p;
p=(int*)malloc(1024*sizeof(int));
now how do find how much has been allocated to p?


You already know. 1024 * sizeof(int) (if malloc()
does not return NULL, in which case it's zero).

-Mike
Nov 14 '05 #7
Anitha Adusumilli wrote:

Hi

AFAIK, its not possible to find the size of array allocated by malloc.
Right.
You provide this value to malloc...so, you are the one who has to keep
track of it.
Right.
usually, a constant say "#define ARRAYSIZE 1024" is used and this
constant is used in malloc and anywhere else the array size needs to be
found


Wrong. This defeats the point of using malloc in the first place.

If you know you need ARRAYSIZE Ts, just use T arr[ARRAYSIZE]. malloc
is useful when you don't know at compile time how many objects you
will need. All the more reason to keep track.
Nov 14 '05 #8
"E. Robert Tisdale" wrote:

ma*******@HotPop.com wrote:
How do I find out inside a program
what size has been allocated to pointer using malloc. e.g.:

It's implementation dependent.


But not implementation-defined. And it's not always possible.
> cat main.c

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

size_t allocation(const void* p) {
return ((size_t*)p)[-1] - 1;


6.5.6 (8): "If both the pointer operand and the result point to
elements of the same array object, or one past the last element
of the array object, the evaluation shall not produce an overflow;
otherwise, the behavior is undefined."

Consequently, the behaviour of this code is undefined.
Nov 14 '05 #9
"E. Robert Tisdale" <E.**************@jpl.nasa.gov> writes:
ma*******@HotPop.com wrote:
How do I find out inside a program
what size has been allocated to pointer using malloc. e.g.:
int *p=(int*)malloc(1024*sizeof(int));
Now how do find how much has been allocated to p?


It's implementation dependent.


Yes. You might as well have stopped there.
> cat main.c [Non-portable code snipped] > gcc -Wall -std=c99 -pedantic -o main main.c
> ./main 1

size = 16


The provided code is useless other than to demonstrate how one
implementation happens to behave. Incidentally, the behavior shown
has nothing to do with gcc; it's a characteristic of the C runtime
library, not of the 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 #10
On Thu, 6 Jan 2005 07:40:28 +0000 (UTC), infobahn
<in******@btinternet.com> wrote:
Anitha Adusumilli wrote:

usually, a constant say "#define ARRAYSIZE 1024" is used and this
constant is used in malloc and anywhere else the array size needs to be
found
Wrong. This defeats the point of using malloc in the first place.


What is 'the' purpose of using malloc? Hint: it isn't just to make
variable sized arrays. How about linked lists, where the size of each
element is known (and may include an array, for instance)?
If you know you need ARRAYSIZE Ts, just use T arr[ARRAYSIZE]. malloc
is useful when you don't know at compile time how many objects you
will need. All the more reason to keep track.


You can try allocating a large object on the stack, but it will fail on
many systems, and having it static may well waste valuable data space.
Using malloc is more usual for that.

Chris C
Nov 14 '05 #11
Chris Croughton wrote:

On Thu, 6 Jan 2005 07:40:28 +0000 (UTC), infobahn
<in******@btinternet.com> wrote:
Anitha Adusumilli wrote:

usually, a constant say "#define ARRAYSIZE 1024" is used and this
constant is used in malloc and anywhere else the array size needs to be
found
Wrong. This defeats the point of using malloc in the first place.


What is 'the' purpose of using malloc?


In the current context (i.e. the context quoted above, and in terms
of which my answer should be read), it's to allocate space for an
array. In other contexts, it can have other purposes (although one
could reasonably argue that malloc always makes space for an array,
even if it's an array only one item in size!).
Hint: it isn't just to make
variable sized arrays. How about linked lists, where the size of each
element is known (and may include an array, for instance)?


I do not dispute that such a useful tool can solve other tasks too. :-)
Nov 14 '05 #12
infobahn wrote:
Chris Croughton wrote:
On Thu, 6 Jan 2005 07:40:28 +0000 (UTC), infobahn
<in******@btinternet.com> wrote:

Anitha Adusumilli wrote:

usually, a constant say "#define ARRAYSIZE 1024" is used and this
constant is used in malloc and anywhere else the array size needs to be
found

Wrong. This defeats the point of using malloc in the first place.


What is 'the' purpose of using malloc?

In the current context (i.e. the context quoted above, and in terms
of which my answer should be read), it's to allocate space for an
array. In other contexts, it can have other purposes (although one
could reasonably argue that malloc always makes space for an array,
even if it's an array only one item in size!).


Who says he didn't interpret it in that context? But nobody said
we were talking about dynamically sized arrays, so his correction
remains, that a compile-time constant is a valid answer. However,
I disagree with Anitha's "usually" part.
Nov 14 '05 #13
infobahn wrote:
...
usually, a constant say "#define ARRAYSIZE 1024" is used and this
constant is used in malloc and anywhere else the array size needs to be
found


Wrong. This defeats the point of using malloc in the first place.

If you know you need ARRAYSIZE Ts, just use T arr[ARRAYSIZE]. malloc
is useful when you don't know at compile time how many objects you
will need. All the more reason to keep track.


Wrong. There at least two situations when 'malloc' might be used with
constant size argument

1. A need for manual control of the object's storage duration (in this
case it is an array).

Your suggestion to use 'T arr[ARRAYSIZE]' won't work simply because the
lifetime of, say, automatic 'arr's would automatically end at the end of
the block. That might be not what's needed.

2. When there's a good reason to believe that the object's size is to
large for, say, automatic memory

--
Best regards,
Andrey Tarasevich
Nov 14 '05 #14
Andrey Tarasevich wrote:

infobahn wrote:
...
usually, a constant say "#define ARRAYSIZE 1024" is used and this
constant is used in malloc and anywhere else the array size needs to be
found
Wrong. This defeats the point of using malloc in the first place.

If you know you need ARRAYSIZE Ts, just use T arr[ARRAYSIZE]. malloc
is useful when you don't know at compile time how many objects you
will need. All the more reason to keep track.


Wrong.


<sigh> /me must remember there ain't no such animal as context in
Usenet.
There at least two situations when 'malloc' might be used with
constant size argument

1. A need for manual control of the object's storage duration (in this
case it is an array).

Your suggestion to use 'T arr[ARRAYSIZE]' won't work simply because the
lifetime of, say, automatic 'arr's would automatically end at the end of
the block. That might be not what's needed.

2. When there's a good reason to believe that the object's size is to
large for, say, automatic memory


You forgot dynamic data structures, and initialisation of dynamic
vectors to a sensible chunk size, to name but two.
Nov 14 '05 #15
>From what the person who originally posted asked, I felt this int array
is used for returning value in a funtion. You cant return
"arr",declared as T arr[ARRAYSIZE], because it is a local
variable..allocated on stack. By using malloc for arrays, u can return
that array and the caller can later deallocate it by "free". Hope my
last pt is clear now.
Anitha

Nov 14 '05 #16
infobahn wrote:
> If you know you need ARRAYSIZE Ts, just use T arr[ARRAYSIZE]. malloc
> is useful when you don't know at compile time how many objects you
> will need. All the more reason to keep track.


Wrong.


<sigh> /me must remember there ain't no such animal as context in
Usenet.


Huh?
There at least two situations when 'malloc' might be used with
constant size argument

1. A need for manual control of the object's storage duration (in this
case it is an array).

Your suggestion to use 'T arr[ARRAYSIZE]' won't work simply because the
lifetime of, say, automatic 'arr's would automatically end at the end of
the block. That might be not what's needed.

2. When there's a good reason to believe that the object's size is to
large for, say, automatic memory


You forgot dynamic data structures, and initialisation of dynamic
vectors to a sensible chunk size, to name but two.


"Dynamic data structures" is quite a generic term. I don't understand
what exactly do you mean by this.

In any case, I didn't try to come up with a complete list of such
situations. It's just a couple of examples.

--
Best regards,
Andrey Tarasevich

Nov 14 '05 #17

ma*******@HotPop.com wrote:
Hi,

Inside a program how do i find out what size has been allocated to
pointer using malloc. eg...

int *p;
p=(int*)malloc(1024*sizeof(int));
now how do find how much has been allocated to p?

mojozoox!

well , i think if malloc has not returned 0 ie failure
then the size allocated is same as that was demanded.

by the way what will sizeof operator applied on p will return.
i think it is the size allocated to pointer p .if that is true
u get ur answer

goodluck

Nov 14 '05 #18
hotadvice wrote:

ma*******@HotPop.com wrote:
Hi,

Inside a program how do i find out what size has been allocated to
pointer using malloc. eg...

int *p;
p=(int*)malloc(1024*sizeof(int));
now how do find how much has been allocated to p?

mojozoox!
well , i think if malloc has not returned 0 ie failure
then the size allocated is same as that was demanded.


At least what was demanded, actually. And of course what you
asked for is all you can rely on having (if, as you say, it
didn't fail).

by the way what will sizeof operator applied on p will return.
i think it is the size allocated to pointer p .if that is true
u get ur answer


sizeof p yields the size of the pointer, not the size of the
thing pointed to.

sizeof *p works if you only asked for space for one object
of that size (and provided p isn't a void *, obviously!).
Nov 14 '05 #19
so finally
1.not returning 0 implies at least the size that was asked is allocated
2.sizeof(*p) gives u th e size

so shall we say pack up

Nov 14 '05 #20
so finally
1.not returning 0 implies at least the size that was asked is allocated
2.sizeof(*p) gives u th e size

so shall we say pack up

Nov 14 '05 #21
so finally
1.not returning 0 implies at least the size that was asked is allocated
2.sizeof(*p) gives u th e size

so shall we say pack up

Nov 14 '05 #22
hotadvice wrote:
so finally
1.not returning 0 implies at least the size that was asked is allocated
Correct.
2.sizeof(*p) gives u th e size
Incorrect (or correct only sometimes, by coincidence).
so shall we say pack up


Surely -- but on the evidence, I'd suggest not packing
up your C textbook quite yet ...

--
Er*********@sun.com

Nov 14 '05 #23
"hotadvice" <am******@rediffmail.com> writes:
so finally
1.not returning 0 implies at least the size that was asked is allocated
Yes.
2.sizeof(*p) gives u th e size

so shall we say pack up


You posted that followup 3 times.

No, sizeof(*p) doesn't give you (that's "you", not "u"; we prefer to
avoid cutesy abbreviations here) the size allocated, it gives you the
size of a single object of the type p points to.

Given:

ptr = malloc(some_size);

there is no portable way, given the value of ptr, to determine the
number of bytes actually allocated. You can determine the number of
bytes *requested*, but only by keeping track of it yourself.

Presumably the system keeps track of the number of bytes actually
allocated (so free() knows what to do), but there's no portable way to
ask the system for this information. If you need to know, your best
bet is to redesign your algorithm so you *don't* need to know.

--
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 #24
In article <ln************@nuthaus.mib.org>,
Keith Thompson <ks***@mib.org> wrote:
Given:

ptr = malloc(some_size);

there is no portable way, given the value of ptr, to determine the
number of bytes actually allocated. You can determine the number of
bytes *requested*, but only by keeping track of it yourself.

Presumably the system keeps track of the number of bytes actually
allocated (so free() knows what to do), but there's no portable way to
ask the system for this information. If you need to know, your best
bet is to redesign your algorithm so you *don't* need to know.


Well put.

Just fyi, there is a proposal before the C committee which includes a
portable way to get this information:

http://www.open-std.org/jtc1/sc22/wg...docs/n1085.htm

This proposal, with alternate __function_names, is now shipping from
Metrowerks for those platforms where we supply the C library. This
functionality is also being used in the std::C++ library to optimize
template classes such as vector in some specialized circumstances.

-Howard
Nov 14 '05 #25
Let me assume it done somewhere in a library and im using it... then
how do i know... ???

mojo

Nov 14 '05 #26
the size requested will be allocated , if that size is not available
then malloc will fail. and u can know the size from the arguments of
malloc and if succesful only that size will be allocated..
ma*******@HotPop.com wrote:
Hi,

Inside a program how do i find out what size has been allocated to
pointer using malloc. eg...

int *p;
p=(int*)malloc(1024*sizeof(int));
now how do find how much has been allocated to p?

mojozoox!


Nov 14 '05 #27
Howard Hinnant wrote:
.... snip ...
Just fyi, there is a proposal before the C committee which includes a
portable way to get this information:

http://www.open-std.org/jtc1/sc22/wg...docs/n1085.htm

This proposal, with alternate __function_names, is now shipping from
Metrowerks for those platforms where we supply the C library. This
functionality is also being used in the std::C++ library to optimize
template classes such as vector in some specialized circumstances.


As proposed it has a fatal flaw. It requires an xxx_malloc() call
to return the actual size allocated via an auxiliary parameter, but
specifies that it must be 0 for a 0 size request. This fouls up
the systems that need a minimum allocation size for one reason or
another.

In addition the user often wants space for some form of array. The
possible overage is likely to be useless since it won't hold a
complete item. The possibility for programmer error boggles the
mind.

--
Chuck F (cb********@yahoo.com) (cb********@worldnet.att.net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home.att.net> USE worldnet address!

Nov 14 '05 #28
"mojozoox" <ma*******@HotPop.com> writes:
Let me assume it done somewhere in a library and im using it... then
how do i know... ???


What is done somewhere in a library? How do you know what?

We can't figure out what you mean if you don't provide any context.

(I took a look at the article you were replying to, but I didn't see
any questions there that haven't already been answered in this
thread.)

--
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 #29
th********@rediffmail.com writes:
ma*******@HotPop.com wrote:
Inside a program how do i find out what size has been allocated to
pointer using malloc. eg...

int *p;
p=(int*)malloc(1024*sizeof(int));
now how do find how much has been allocated to p?


the size requested will be allocated , if that size is not available
then malloc will fail. and u can know the size from the arguments of
malloc and if succesful only that size will be allocated..


Please don't top-post.

In fact, a successful malloc() can, and often does, allocate more
bytes than were requested. (It's common for the size to be rounded up
to a multiple of some block size, or to a power of 2.) But the
language provides no portable way to find out how many bytes were
actually allocated.

--
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
On 7 Jan 2005 19:54:23 -0800, in comp.lang.c , "mojozoox"
<ma*******@HotPop.com> wrote:
Let me assume it done somewhere in a library and im using it... then
how do i know... ???


How do you know what? Please retain some context when posting, and remember
not everyone has read the thread from the start.
--
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 #31
On 7 Jan 2005 10:39:23 -0800, "hotadvice" <am******@rediffmail.com>
wrote:
<snip>
2.sizeof(*p) gives u th e size


Sorry, three wrongs do not make you right.

And three u's do not make youse (or y'all). Is Y O U really too hard
to type?

--
Sev
Nov 14 '05 #32
In article <41***************@yahoo.com>,
CBFalconer <cb********@yahoo.com> wrote:
Howard Hinnant wrote:
... snip ...

Just fyi, there is a proposal before the C committee which includes a
portable way to get this information:

http://www.open-std.org/jtc1/sc22/wg...docs/n1085.htm

This proposal, with alternate __function_names, is now shipping from
Metrowerks for those platforms where we supply the C library. This
functionality is also being used in the std::C++ library to optimize
template classes such as vector in some specialized circumstances.


Thank you for your comments. I am most open and interested in improving
this proposal in any way possible.
As proposed it has a fatal flaw. It requires an xxx_malloc() call
to return the actual size allocated via an auxiliary parameter, but
specifies that it must be 0 for a 0 size request. This fouls up
the systems that need a minimum allocation size for one reason or
another.
It is specified only that request_malloc return 0,0 given a 0 size
request. This behavior is trivial to implement on any system. Indeed
the proposal shows a portable implementation.

It is not proposed that malloc must return 0 for a 0 size request. Nor
is it required that sizeof_alloc(malloc(0)) return 0.

However I would gladly change the proposal to require that
request_malloc(0, 0) return non-null on success. My intent here is that
request_malloc have well defined and portable behavior for 0-sized
requests, in contrast to the current behavior for malloc(0) which is
implementation defined. I see no motivation for malloc(0) to be
implementation defined except for (non-portable) backwards
compatibility. And request_malloc has no backwards compatibility
concerns.
In addition the user often wants space for some form of array. The
possible overage is likely to be useless since it won't hold a
complete item. The possibility for programmer error boggles the
mind.


If the sizeof(array-element) < the system alignment / 2, there is a good
chance that the overage will hold a complete item. If it is >= the
system alignment / 2 then I agree that the overage is likely to be
useless. Ignoring that this extra memory exists (when it can be
utilized) doesn't seem logical to me.

As for the possibility for programmer error, I agree that one must
always design interfaces and behavior so that the library is as safe as
possible while still providing the needed functionality. I'm currently
at a loss as how to lesson the dangers you perceive, while still
providing this useful functionality.

Perhaps a future rewrite of this proposal will use a non-char-sized
array as an example. This might better demonstrate how to take
advantage of the extra memory:

void
construct_int_array(int_array* array, size_t size)
{
array->data = 0;
array->size = array->capacity = 0;
if (size)
{
size_t size_received;
array->data = request_malloc(size*sizeof(int), &size_received);
size_received /= sizeof(int); // mind boggling error prone?
if (array->data == 0)
on_error(size_received);
array->capacity = size_received;
array->size = size;
}
}

It seems no more error prone to me than having to adjust your requested
size by the size of your element.

-Howard
Nov 14 '05 #33
On Fri, 07 Jan 2005 10:39:23 -0800, hotadvice wrote:
so finally
1.not returning 0 implies at least the size that was asked is allocated
2.sizeof(*p) gives u th e size


No.

int *ptr = malloc( 100 * sizeof(int) );
size_t s = sizeof( *ptr );

s does _not_ equal 100*sizeof(int), it equals the size of *one* int.
Nov 14 '05 #34
Howard Hinnant wrote:
CBFalconer <cb********@yahoo.com> wrote:
.... snip ...
As proposed it has a fatal flaw. It requires an xxx_malloc() call
to return the actual size allocated via an auxiliary parameter, but
specifies that it must be 0 for a 0 size request. This fouls up
the systems that need a minimum allocation size for one reason or
another.


It is specified only that request_malloc return 0,0 given a 0 size
request. This behavior is trivial to implement on any system.
Indeed the proposal shows a portable implementation.

It is not proposed that malloc must return 0 for a 0 size request.
Nor is it required that sizeof_alloc(malloc(0)) return 0.


You have specified that request_malloc is shorthand for a sequence
involving malloc and sizeof_alloc. The response cannot be
different, and should not, because such differences create major
confusion.

One system that I created changes all 0 size requests to 1. You
can see the system on my pages, download section, nmalloc.zip. The
reason is that once the allocation is freed it has to go into the
appropriate free list, and needs further links. The actual (now
unused) allocation space (rounded up) can supply this, for a
non-zero size.

Lying back to the user about the actual size defeats the whole
purpose of the arrangement, which is to allow expansion without
system calls. In nmalloc, if you request 0 you will actually get
at least ALIGN bytes (which happens to be 8), possibly more if a
residue is too small to be of use in forming another allocation.

So malloc(0) will normally return non-NULL, and as many as 32 bytes
may be available in my system. For that package at least 8 bytes
will be available. For malloc in general, 0 bytes may be
available. After all, a void* points to void.

--
Chuck F (cb********@yahoo.com) (cb********@worldnet.att.net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home.att.net> USE worldnet address!
Nov 14 '05 #35
In article <41***************@yahoo.com>,
CBFalconer <cb********@yahoo.com> wrote:
You have specified that request_malloc is shorthand for a sequence
involving malloc and sizeof_alloc. The response cannot be
different, and should not, because such differences create major
confusion.
You are right that the proposal summarizes:
This call is intended to encapsulate a call to malloc and a call to
sizeof_alloc into a single function.
Then the postcondition goes on to state exactly what request_malloc
does, and it may be different for the 0 requested size case (depending
upon how malloc is implemented).

Thank you for pointing out this contradiction. If I get a chance to
rewrite this proposal, I will try to correct that.

The only difference I wish to see between malloc and request_malloc for
zero-sized requests is portable behavior. The behavior of malloc(0)
isn't portable and I wish for the behavior of request_malloc(0,0) to be
portable. That should've been made clear in the proposal.
One system that I created changes all 0 size requests to 1.
<nod> I've used the same technique in some malloc systems I've written.
You
can see the system on my pages, download section, nmalloc.zip.
Thank you for the link.
The
reason is that once the allocation is freed it has to go into the
appropriate free list, and needs further links. The actual (now
unused) allocation space (rounded up) can supply this, for a
non-zero size.
Yet even though your malloc(0) always returns non-null, free(0) must
still respond appropriately (as yours does modulo an optional? warning).

From 7.20.3.2p2:
If ptr is a null pointer, no action occurs. Lying back to the user about the actual size defeats the whole
purpose of the arrangement, which is to allow expansion without
system calls.
I have no desire for the proposed interface to lie to the client. I
wish for the interface to be portable. malloc(0) is not. It may return
0, or it may not. From 7.20.3p1:
If the size of the space requested is zero, the behavior is
implementation defined: either a null pointer is returned, or the behavior is
as if the size were some nonzero value, except that the returned pointer
shall not be used to access an object.
I have implemented both interfaces on several platforms, both hosted and
freestanding (though malloc is an extension on freestanding platforms).
I have had no difficulty in offering both interfaces on all platforms,
save backward compatibility issues.
In nmalloc, if you request 0 you will actually get
at least ALIGN bytes (which happens to be 8), possibly more if a
residue is too small to be of use in forming another allocation.

So malloc(0) will normally return non-NULL, and as many as 32 bytes
may be available in my system. For that package at least 8 bytes
will be available.


<nod> I see no reason that you could not layer request_malloc, as
proposed, on nmalloc. It simply would check for the 0 case and return 0
before calling nmalloc. Alternatively, if nmalloc were to be rewritten
and layered on request_malloc, it would do as it does now: check for 0
and change it to 1 if found.

I'm clearly not understanding your concern, and I would like to. Sorry
if I'm just being dense.

What would be your preference:

1. request_malloc(0,0) return 0
2. request_malloc(0,0) return nonzero
3. request_malloc(0,0) return 0 or nonzero, implementation defined

?

I'm arguing for 1 or 2, with a slight preference for 1. But I would
really like to avoid 3. I believe it would make portable programs
harder to write, with no real advantage coming from that cost.

I prefer 1 because it requires less heap to implement it. And I am
sensitive to resource constrained (embedded) environments.

-Howard
Nov 14 '05 #36
Howard Hinnant wrote:
.... snip ...
What would be your preference:

1. request_malloc(0,0) return 0
2. request_malloc(0,0) return nonzero
3. request_malloc(0,0) return 0 or nonzero, implementation defined


You don't have any of those cases. IIRC your prototype is:

void *request_malloc(size_t sz, size_t *actual);

which returns a pointer (NULL for failure), and the actual size
available on success. The logic of the situation insists that
*actual be >= sz on success, else undefined. It can be simulated
(assuming sizeof_malloc() exists) with:

void *request_malloc(size_t sz, size_t *actual)
{
void *p;

if (p = malloc(sz)) *actual = sizeof_malloc(p);
return p;
}

and I consider any other behaviour a contortion.

--
Chuck F (cb********@yahoo.com) (cb********@worldnet.att.net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home.att.net> USE worldnet address!
Nov 14 '05 #37
In article <41***************@yahoo.com>,
CBFalconer <cb********@yahoo.com> wrote:
Howard Hinnant wrote:

... snip ...

What would be your preference:

1. request_malloc(0,0) return 0
2. request_malloc(0,0) return nonzero
3. request_malloc(0,0) return 0 or nonzero, implementation defined


You don't have any of those cases. IIRC your prototype is:

void *request_malloc(size_t sz, size_t *actual);

which returns a pointer (NULL for failure), and the actual size
available on success. The logic of the situation insists that
*actual be >= sz on success, else undefined. It can be simulated
(assuming sizeof_malloc() exists) with:

void *request_malloc(size_t sz, size_t *actual)
{
void *p;

if (p = malloc(sz)) *actual = sizeof_malloc(p);
return p;
}

and I consider any other behaviour a contortion.


The proposal shows how request_malloc can be simulated with malloc, and
also states that actual is allowed to be null, in which case *actual
should not be written to.

From your version of the request_malloc simulation, you have chosen 3
(implementation defined behavior for zero sized requests).

Thanks,
-Howard
Nov 14 '05 #38
Howard Hinnant wrote:
CBFalconer <cb********@yahoo.com> wrote:

.... snip ...

void *request_malloc(size_t sz, size_t *actual)
{
void *p;

if (p = malloc(sz)) *actual = sizeof_malloc(p);
return p;
}

and I consider any other behaviour a contortion.


The proposal shows how request_malloc can be simulated with malloc,
and also states that actual is allowed to be null, in which case
*actual should not be written to.

From your version of the request_malloc simulation, you have chosen
3 (implementation defined behavior for zero sized requests).


Disagree. I have choses "semantically consistent". The null
actual can be handled with:

if ((p = malloc(sz)) && actual) *actual = sizeof_malloc(p);

--
Chuck F (cb********@yahoo.com) (cb********@worldnet.att.net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home.att.net> USE worldnet address!
Nov 14 '05 #39
Groovy hepcat ma*******@HotPop.com was jivin' on 5 Jan 2005 19:29:18
-0800 in comp.lang.c.
malloc size's a cool scene! Dig it!
Inside a program how do i find out what size has been allocated to
pointer using malloc. eg...


**** Read the bloody FAQ and lurk, for crying out loud! ****

It is very rude to post to a newsgroup before lurking for some time
and reading its FAQ. It exists so that you don't have to ask this
question and others like it, since quintillions of people have already
asked, some within the last few weeks or even days, and millions of
others have already answered trillions of times. (Slight exageration.)
Go to http://www.eskimo.com/~scs/C-faq/top.html and read it all.
Then read a couple months of posts in this newsgroup. If your question
is still unanswered, repeat both of these steps until it is answered.

--

Dig the even newer still, yet more improved, sig!

http://alphalink.com.au/~phaywood/
"Ain't I'm a dog?" - Ronny Self, Ain't I'm a Dog, written by G. Sherry & W. Walker.
I know it's not "technically correct" English; but since when was rock & roll "technically correct"?
Nov 14 '05 #40
On Fri, 07 Jan 2005 19:54:23 -0800, mojozoox wrote:
Let me assume it done somewhere in a library and im using it... then
how do i know... ???


If you mean how do you know how big an object allocated by a library is
then the answer is that you don't unless the library provides a
specification or programmatic means to tell you. If a library returns a
pointer to an allocated object there should be a clear specification of
what you can do with it. Trying to find out information that it doesn't
tell you is probably an error.

Lawrence
Nov 14 '05 #41

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

Similar topics

19
by: john smith | last post by:
Can someone please explain to me what is happening when I do a malloc(0). This is what I did. int* p = (int*)malloc(0); Then I printed the value of p and of course it was non-null. But...
13
by: mike79 | last post by:
hi all.. if I wanted to malloc a struct, say the following: struct myStruct1 { int number; char *string; }
10
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
54
by: Neo | last post by:
Hi Folks, I've a simple qestion related to dynamic memory allocation in C here is the code: #include <stdio.h> int main() {
18
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...
58
by: Jorge Peixoto de Morais Neto | last post by:
I was reading the code of FFmpeg and it seems that they use malloc just too much. The problems and dangers of malloc are widely known. Malloc also has some overhead (although I don't know what is...
71
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...
3
by: Petr Pavlu | last post by:
Hello, I have two questions how the functions should be written. I read the FAQ but didn't find any answer. If there is any please point me out. I. Cleanup code Consider I have to open file1,...
10
by: somenath | last post by:
Hi All, I have one question regarding return value cast of malloc. I learned that we should not cast the return value of malloc because it is bug hider. But my question is as mentioned...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.