what does malloc(0) return? [duplicate]

2019-01-03 15:29发布

This question already has an answer here:

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;
}

9条回答
可以哭但决不认输i
2楼-- · 2019-01-03 15:55

I think it depends. I checked the Visual Studio 2005 sources and saw this in the _heap_alloc function:

if (size == 0)
    size = 1;

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.

查看更多
兄弟一词,经得起流年.
3楼-- · 2019-01-03 16:01

If malloc(0) returns dummy pointer, then how does following works:

void *ptr = malloc(0);

printf("%p\n", realloc(ptr, 1024));

I don't know what you mean by "dummy pointer". If malloc(0) returns non-NULL, then ptr is a valid pointer to a memory block of size zero. The malloc implementation saves this information in an implementation-specific way. realloc knows the (implementation-specific) way to figure out that ptr 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 is 0. You should never do this from your code, it's only for use by realloc and free).

查看更多
Anthone
4楼-- · 2019-01-03 16:05

C99 standard

If the space cannot be allocated, a nullpointer is returned. 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.

查看更多
迷人小祖宗
5楼-- · 2019-01-03 16:07

One point nobody cared to talk about yet, in your first program is that realloc with length 0 is the same thing as free.

from the Solaris man page:

The realloc() function changes the size of the block pointed to by ptr to size bytes and returns a pointer to the (possibly moved) block. The contents will be unchanged up to the lesser of the new and old sizes. If ptr is NULL, realloc() behaves like malloc() for the specified size. If size is 0 and ptr is not a null pointer, the space pointed to is made available for further allocation by the application, though not returned to the system. Memory is returned to the system only upon termination of the application.

If one doesn't know that it can be a source of bad surprise (happened to me).

查看更多
我想做一个坏孩纸
6楼-- · 2019-01-03 16:09

See C99, section 7.20.3:

If the size of the space requested is zero, the behavior is implementationdefined: 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.

This is valid for all three allocation functions (ie calloc(), malloc() and realloc()).

查看更多
聊天终结者
7楼-- · 2019-01-03 16:13

malloc(0) is Implementation Defined as far as C99 is concerned.

From C99 [Section 7.20.3]

The order and contiguity of storage allocated by successive calls to the calloc, malloc, and realloc functions is unspecified. The pointer returned if the allocation succeeds is suitably aligned so that it may be assigned to a pointer to any type of object and then used to access such an object or an array of such objects in the space allocated (until the space is explicitly deallocated). The lifetime of an allocated object extends from the allocation until the deallocation. Each such allocation shall yield a pointer to an object disjoint from any other object. The pointer returned points to the start (lowest byte address) of the allocated space. 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: 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.

查看更多
登录 后发表回答