This question already has an answer here:
- what's the point in malloc(0)? 16 answers
What does malloc(0)
returns? Would the answer be same for realloc(malloc(0),0)
?
#include<stdio.h>
#include<malloc.h>
int main()
{
printf("%p\n", malloc(0));
printf("%p\n", realloc(malloc(0), 0));
return 0;
}
Output from linux gcc:
manav@manav-workstation:~$ gcc -Wall mal.c
manav@manav-workstation:~$ ./a.out
0x9363008
(nil)
manav@manav-workstation:~$
The output keep changing everytime for malloc(0)
. Is this a standard answer? And why would anyone be interested in getting such a pointer, other than academic research?
EDIT:
If malloc(0)
returns dummy pointer, then how does following works:
int main()
{
void *ptr = malloc(0);
printf("%p\n", realloc(ptr, 1024));
return 0;
}
EDIT:
The following code outputs "possible" for every iteration. Why should it not fail ?
#include<stdio.h>
#include<malloc.h>
int main()
{
int i;
void *ptr;
printf("Testing using BRUTE FORCE\n");
for (i=0; i<65000; i++)
{
ptr = malloc(0);
if (ptr == realloc(ptr, 1024))
printf("Iteration %d: possible\n", i);
else
{
printf("Failed for iteration %d\n", i);
break;
}
}
return 0;
}
I think it depends. I checked the Visual Studio 2005 sources and saw this in the _heap_alloc function:
I think that in many cases you may want a valid pointer, even when asking for zero bytes. This is because this consistent behavior makes it easier to check your pointers because: if you have a non-NULL pointer it's OK; if you have a NULL pointer you probably have a problem. That's why I think that most implementations will return a valid pointer, even when asking for zero bytes.
I don't know what you mean by "dummy pointer". If
malloc(0)
returns non-NULL, thenptr
is a valid pointer to a memory block of size zero. Themalloc
implementation saves this information in an implementation-specific way.realloc
knows the (implementation-specific) way to figure out thatptr
points to a memory block of size zero.(How
malloc
/realloc
/free
do this is implementation-specific. One possibility is to allocate 4 bytes more than requested and store the size just before the memory block. In that case,((int *)ptr)[-1]
would give the memory block size, which is0
. You should never do this from your code, it's only for use byrealloc
andfree
).C99 standard
One point nobody cared to talk about yet, in your first program is that
realloc
with length 0 is the same thing asfree
.from the Solaris man page:
If one doesn't know that it can be a source of bad surprise (happened to me).
See C99, section 7.20.3:
This is valid for all three allocation functions (ie
calloc()
,malloc()
andrealloc()
).malloc(0)
is Implementation Defined as far as C99 is concerned.From C99 [Section 7.20.3]