zero sized allocation using malloc on AIX !

what happens when we try to allocate 0 bytes memory using malloc() ? My assumption was that memory will not be allocated but see what happened ! I tried it on two operating system environments – Linux and AIX (whose behaviour I heard is different from ‘default’) following is the linux version of the code :-

int main()
{
    int *p = 0;
    printf("before addr: %pn", p);
    p = (int *) malloc(0);
    printf("after addr: %pn", p);
    printf("sizeof: %un", sizeof(*p));
    *p = 1;
    printf("--- %d -- this is the last statment.n", *p);
    free(p);
}

and when run, produces following output on my shell,

[root@localhost work]# ./alloc
before addr: (nil)
after addr: 0x80496c8
sizeof: 4
--- 1 -- this is the last statment.

and this is the AIX version :-

#include 

int main()
{
int *p, *q = 0x0;
printf("before addr : %pn", p);
p = (int *) malloc(0);
printf("after addre : %p %dn", p, *p);
free(p);
}

and the output goes here:

fundu[/manoj]: ./alloc
before addr : 2ff22ca8
after addre : 0 0
sizeof: 4 4

when I tried using the memory allocated in AIX program, using

*p = 1;

it segfaulted as expected by me !

So, AIX

  • allows a ‘read’ of the zero sized allocated memory
  • DOES NOT allow a ‘write’ on the zero sized allocated memory
  • sizeof shows an allocation of 4 bytes.

while Linux

  • allows a ‘read’ of the zero sized allocated memory
  • allows a ‘write’ on the zero sized allocated memory
  • sizeof shows an allocation of 4 bytes.

.. strange. but led me to ‘google’. following are the links I found interesting:

and following is a snip from a mailing list:

>
> I've tracked down the problem to change (somewhere) in 2.2.0 vs. 2.1.1 which
> has
> resulted in re_node_set_alloc() (in src/main/regex.c) being called with a
> size
> of 0.
> Whereas some system (Solaris, Linux, ...) return a valid pointer to a
> zero-size allocation, OSF1 returns a NULL pointer on a 0 allocation
> request
> (documented as such, and the Open Group Base Specifications Issue 6 documents
> that either may happen). The calling code treats a NULL return as a ESPACE
> error.
>

About these ads

2 thoughts on “zero sized allocation using malloc on AIX !

  1. Hi there !

    Take care : sizeof(*p) is evaluated at compile time, therefore if will never be different of the size of an int as you declared p as int *p;

    Interesting blog, I’ll come back by ;-)

    St├ęphane

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s