473,322 Members | 1,610 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,322 software developers and data experts.

malloc (0)

Hey can any one tell me what malloc 0 does, it assigns space in memory
i know that but is it usable and how many bytes does it allocate ,
allocation of 0 bytes is difficult-to-digest concept and still in the
memory.

Jul 4 '06 #1
14 12175

Bhaskar wrote:
Hey can any one tell me what malloc 0 does, it assigns space in memory
i know that but is it usable and how many bytes does it allocate ,
allocation of 0 bytes is difficult-to-digest concept and still in the
memory.

I believe it returns NULL.
You're asking for 0 (no) memory to be allocated by doing malloc(0).

Jul 4 '06 #2
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
Bhaskar wrote:
Hey can any one tell me what malloc 0 does,
ITYM
malloc(0);

And, the answer is yes and no.
it assigns space in memory i know that
Well, you know wrong, then
but is it usable and how many bytes does it allocate ,
FWIW, you ask for 0 bytes, you might just get zero bytes
allocation of 0 bytes is difficult-to-digest concept and still in the
memory.
The C standards (actually, the draft) says

7.20.3 Memory management functions
[snip]
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.

The key phrase is "implementation defined". That means that we can't
answer your questions (or even grant that your assertions are correct
or not) without knowing the details of the C implementation you are
using. As I read it, so long as your C compiler/environment's
implementation documents it, malloc(0) could legitimately launch
Russian ICBM missles at your house or cause daemons to fly out of your
nose (the dreaded nasal daemons). Or, it could manipulate its
underlying storage management components so as to remove zero
user-accessable bytes of storage from the appropriate pool of free
storage and place it in a pool of used storage (such an operation would
likely involve an internal allocation of 0+n bytes, where the n
represents the data management overhead).

HTH

- --
Lew Pitcher

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.3 (MingW32) - WinPT 0.11.12

iD8DBQFEqrmCagVFX4UWr64RAt3pAKCDJTOLbg+DhrtriNiA4P WSbKbJXACfSrtI
Axh2N6HHw/XOOkpbvGYYb2g=
=cE92
-----END PGP SIGNATURE-----

Jul 4 '06 #3
"Kiru Sengal" <ki*********@gmail.comwrites:
Bhaskar wrote:
Hey can any one tell me what malloc 0 does, it assigns space in memory
i know that but is it usable and how many bytes does it allocate ,
allocation of 0 bytes is difficult-to-digest concept and still in the
memory.

I believe it returns NULL.
I don't think so:

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

int main(int argc, char **argv){
int *i = (int *)malloc(0);

printf("%p\n", (void *)i);
printf("%p\n", NULL);
return 0;
}

output me:
toto@epia ~ $ ./a.out
0x804a050
(nil)
Jul 4 '06 #4
Lew Pitcher wrote:
Bhaskar wrote:
Hey can any one tell me what malloc 0 does,

ITYM
malloc(0);

And, the answer is yes and no.
it assigns space in memory i know that

Well, you know wrong, then
but is it usable and how many bytes does it allocate ,

FWIW, you ask for 0 bytes, you might just get zero bytes
allocation of 0 bytes is difficult-to-digest concept and still in the
memory.

The C standards (actually, the draft) says

7.20.3 Memory management functions
[snip]
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.

The key phrase is "implementation defined". That means that we can't
answer your questions (or even grant that your assertions are correct
or not) without knowing the details of the C implementation you are
using. As I read it, so long as your C compiler/environment's
implementation documents it, malloc(0) could legitimately launch
Russian ICBM missles at your house or cause daemons to fly out of your
nose (the dreaded nasal daemons).
"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."

Unless either returning a null pointer by itself in a user function, or
calling malloc with a nonzero size, is allowed to launch missiles, no,
malloc(0) isn't allowed to launch missiles either. Either it just
returns a null pointer, or it behaves (almost) as, for example,
malloc(1).

Jul 4 '06 #5

"Bhaskar" <bh***********@gmail.comwrote in message
news:11**********************@75g2000cwc.googlegro ups.com...
Hey can any one tell me what malloc 0 does, it assigns space in memory
i know that but is it usable and how many bytes does it allocate ,
allocation of 0 bytes is difficult-to-digest concept and still in the
memory.
It can either return a pointer to a block of no length, or it can return a
null pointer.

A block of no length might seem a slightly Hindu concept, but it is not that
difficult for anyone to understand, even if they don't apprecuiate all the
subtleties of zero..
Imagine a control block of 8 bytes which gieves information about the memory
allocated, so that free() can return it properly to the pool. malloc returns
a pointer to the meory immediately after this block.

Now image we allocate block A, of 4 bytes, and block B od zero bytes, the
block C of 4 bytes.

AAAAAAAAaaaaBBBBBBBBCCCCCCCCcccc
^ ^ ^

The Chinese hats represent the pointers returned. When we call free(),
internally 8 bytes are subtracted and this tells the system where the
control information is.


--
Buy my book 12 Common Atheist Arguments (refuted)
$1.25 download or $7.20 paper, available www.lulu.com/bgy1mm
Jul 4 '06 #6
"Lew Pitcher" <lp******@sympatico.cawrites:
[...]
The key phrase is "implementation defined". That means that we can't
answer your questions (or even grant that your assertions are correct
or not) without knowing the details of the C implementation you are
using.
Correct.
As I read it, so long as your C compiler/environment's
implementation documents it, malloc(0) could legitimately launch
Russian ICBM missles at your house or cause daemons to fly out of your
nose (the dreaded nasal daemons).
[snip]

No. It's implementation-defined behavior, not undefined behavior.

--
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.
Jul 4 '06 #7
Keith Thompson wrote:
"Lew Pitcher" <lp******@sympatico.cawrites:
[...]
>The key phrase is "implementation defined". That means that we can't
answer your questions (or even grant that your assertions are correct
or not) without knowing the details of the C implementation you are
using.

Correct.
> As I read it, so long as your C compiler/environment's
implementation documents it, malloc(0) could legitimately launch
Russian ICBM missles at your house or cause daemons to fly out of your
nose (the dreaded nasal daemons).
[snip]

No. It's implementation-defined behavior, not undefined behavior.
And in either case, the return value of malloc(0) is safe to pass
to free.

Jul 4 '06 #8
Nils O. Selåsdal wrote:
Keith Thompson wrote:
>"Lew Pitcher" <lp******@sympatico.cawrites:
[...]
>>The key phrase is "implementation defined". That means that we can't
answer your questions (or even grant that your assertions are correct
or not) without knowing the details of the C implementation you are
using.

Correct.
>> As I read it, so long as your C compiler/environment's
implementation documents it, malloc(0) could legitimately launch
Russian ICBM missles at your house or cause daemons to fly out of your
nose (the dreaded nasal daemons).
[snip]

No. It's implementation-defined behavior, not undefined behavior.

And in either case, the return value of malloc(0) is safe to pass
to free.
True, but this is really about the standard behaviour for free(), rather
than anything specific to malloc() or its return. That is, the standard
says that when passing a null pointer to free() it does nothing.
Jul 4 '06 #9
Bhaskar wrote:
Hey can any one tell me what malloc 0 does, it assigns space in memory
i know that but is it usable and how many bytes does it allocate ,
allocation of 0 bytes is difficult-to-digest concept and still in the
memory.
Try this.

#include <stdio.h>
#include <stdlib.h>
int main(void) {
void *vp = malloc(0);
printf("malloc(0) returned %p\n", vp);
return 0;
}

Here at home,

malloc(0) returned 902a0

vp is non-null and so I assume that malloc did what I asked and
allocated 0 bytes successfully. Do you think I should free(vp) to avoid
a leak?

--
Joe Wright
"Everything should be made as simple as possible, but not simpler."
--- Albert Einstein ---
Jul 4 '06 #10
Joe Wright wrote:
Bhaskar wrote:
>Hey can any one tell me what malloc 0 does, it assigns space in memory
i know that but is it usable and how many bytes does it allocate ,
allocation of 0 bytes is difficult-to-digest concept and still in the
memory.
Try this.

#include <stdio.h>
#include <stdlib.h>
int main(void) {
void *vp = malloc(0);
printf("malloc(0) returned %p\n", vp);
return 0;
}

Here at home,

malloc(0) returned 902a0

vp is non-null and so I assume that malloc did what I asked and
allocated 0 bytes successfully. Do you think I should free(vp) to avoid
a leak?
Not in this program, but in general yes! Otherwise, you
may well leak some extra "bookkeeping" memory that malloc()
uses to keep track of each zero-length allocation. Try

#include <stdio.h>
#include <stdlib.h>
int main(void) {
unsigned long count = 0;
while (malloc(0) != NULL) {
if (++count == 0) {
printf ("More than %lu successful allocations"
" -- giving up.\n", (unsigned long)-1);
return 0;
}
}
printf ("%lu successful allocations before NULL\n",
count);
return 0;
}

"Here at home," I get

72960776 successful allocations before NULL

.... plus a lot of disk activity and some system alerts about
increasing the size of the page file. Strongly suggestive of
leakage, I'd say.

--
Eric Sosman
es*****@acm-dot-invalid.org
Jul 4 '06 #11
Eric Sosman wrote:
Joe Wright wrote:
>Bhaskar wrote:
>>Hey can any one tell me what malloc 0 does, it assigns space in memory
i know that but is it usable and how many bytes does it allocate ,
allocation of 0 bytes is difficult-to-digest concept and still in the
memory.
Try this.

#include <stdio.h>
#include <stdlib.h>
int main(void) {
void *vp = malloc(0);
printf("malloc(0) returned %p\n", vp);
return 0;
}

Here at home,

malloc(0) returned 902a0

vp is non-null and so I assume that malloc did what I asked and
allocated 0 bytes successfully. Do you think I should free(vp) to
avoid a leak?

Not in this program, but in general yes! Otherwise, you
may well leak some extra "bookkeeping" memory that malloc()
uses to keep track of each zero-length allocation. Try

#include <stdio.h>
#include <stdlib.h>
int main(void) {
unsigned long count = 0;
while (malloc(0) != NULL) {
if (++count == 0) {
printf ("More than %lu successful allocations"
" -- giving up.\n", (unsigned long)-1);
return 0;
}
}
printf ("%lu successful allocations before NULL\n",
count);
return 0;
}

"Here at home," I get

72960776 successful allocations before NULL

... plus a lot of disk activity and some system alerts about
increasing the size of the page file. Strongly suggestive of
leakage, I'd say.
Leaks like a sieve. 73 million useless calls to malloc(0) and you
couldn't free() them if you wanted to. Crash and Burn.

--
Joe Wright
"Everything should be made as simple as possible, but not simpler."
--- Albert Einstein ---
Jul 4 '06 #12
On 4 Jul 2006 12:20:41 -0700, in comp.lang.c , "Harald van D?k"
<tr*****@gmail.comwrote:
>Lew Pitcher wrote:
>The key phrase is "implementation defined".
....
>>As I read it, so long as your C compiler/environment's
implementation documents it, malloc(0) could legitimately launch
Russian ICBM missles
>Unless either returning a null pointer by itself in a user function, or
calling malloc with a nonzero size, is allowed to launch missiles, no,
malloc(0) isn't allowed to launch missiles either.
Actually it is, but the implementation must define this behaviour. The
DS9K's C compiler provides a very similar feature.
--
Mark McIntyre

"Debugging is twice as hard as writing the code in the first place.
Therefore, if you write the code as cleverly as possible, you are,
by definition, not smart enough to debug it."
--Brian Kernighan
Jul 4 '06 #13
Mark McIntyre wrote:
On 4 Jul 2006 12:20:41 -0700, in comp.lang.c , "Harald van D?k"
<tr*****@gmail.comwrote:
>Lew Pitcher wrote:
>>The key phrase is "implementation defined".
...
>>As I read it, so long as your C compiler/environment's
implementation documents it, malloc(0) could legitimately launch
Russian ICBM missles
>Unless either returning a null pointer by itself in a user function, or
calling malloc with a nonzero size, is allowed to launch missiles, no,
malloc(0) isn't allowed to launch missiles either.

Actually it is, but the implementation must define this behaviour. The
DS9K's C compiler provides a very similar feature.
Although it hardly matters in this less than serious context, the DS9K
compiler would not be conforming for doing so. (Which would be odd to say
the least, since the DS9K manufacturer is usually very careful about this
sort of thing.)

N1124:
"3.4.1 implementation-defined behavior
unspecified behavior where each implementation documents how the choice is made"

"3.4.4 unspecified behavior
use of an unspecified value, or other behavior where this International
Standard provides two or more possibilities and imposes no further
requirements on which is chosen in any instance"

Even the most liberal interpretation of these statements requires that, if
the standard gives a choice between behaviors and states the actual behavior
is "implementation-defined", then the choice must be made from the behaviors
given and the choice itself must be documented. The implementation is not
allowed to implement additional or replacement behavior, not even if it
documents it.

The alternative would make "unspecified behavior" a synonym for "undefined
behavior", which is clearly not the intent.

S.
Jul 4 '06 #14
"Kiru Sengal" <ki*********@gmail.comwrites:
Bhaskar wrote:
>Hey can any one tell me what malloc 0 does, it assigns space in memory
i know that but is it usable and how many bytes does it allocate ,
allocation of 0 bytes is difficult-to-digest concept and still in the
memory.

I believe it returns NULL.
This is one possible implementation.
It may also return a unique address that may not be dereferenced.
--
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;}
Jul 5 '06 #15

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...
34
by: Richard Hunt | last post by:
I'm sorry for asking such a silly question, but I can't quite get my head around malloc. Using gcc I have always programmed in a lax C/C++ hybrid (which I suppose is actually c++). But I have...
231
by: Brian Blais | last post by:
Hello, I saw on a couple of recent posts people saying that casting the return value of malloc is bad, like: d=(double *) malloc(50*sizeof(double)); why is this bad? I had always thought...
7
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...
20
by: spasmous | last post by:
main() { float * f; initialize_f(f); // ...use f for processing free(f); }
15
by: Martin Jørgensen | last post by:
Hi, I have a (bigger) program with about 15-30 malloc's in it (too big to post it here)... The last thing I tried today was to add yet another malloc **two_dimensional_data. But I found out that...
68
by: James Dow Allen | last post by:
The gcc compiler treats malloc() specially! I have no particular question, but it might be fun to hear from anyone who knows about gcc's special behavior. Some may find this post interesting;...
40
by: Why Tea | last post by:
What happens to the pointer below? SomeStruct *p; p = malloc(100*sizeof(SomeStruct)); /* without a cast */ return((void *)(p+1)); /* will the returned pointer point to the 2nd...
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...
23
by: raphfrk | last post by:
I am having an issue with malloc and gcc. Is there something wrong with my code or is this a compiler bug ? I am running this program: #include <stdio.h> #include <stdlib.h> typedef...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: 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...
0
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...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

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

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