[cfe-commits] [PATCH 1/1] Checking zero byte allocation for realloc() and calloc().
tipecaml at gmail.com
Sat Nov 26 20:26:49 PST 2011
On 11/19/2011 05:35 AM, Jordy Rose wrote:
> I didn't look into the patch in detail, but it's worth noting that realloc can be safe with a 0 size on BSD, at least. ("If size is zero and ptr is not NULL, a new, minimum sized object is allocated and the original object is freed." but "If ptr is NULL, realloc() is identical to a call to malloc() for size bytes.")
> Also, how much overlap is there with MallocChecker? There's a fixme on CheckMallocZero already about having malloc-related checks in two places.
So, here is a new version of the patch :
* Remove all the malloc-related code from the UnixAPIChecker
* Remove the malloc-related tests from test/Analysis/unix-fns.c
* Check zero byte allocations for the malloc(), calloc() and realloc()
functions in the MallocChecker
* Add tests in test/Analysis/malloc.c
About the realloc function, the C99 standard specifies that "if ptr is a
null pointer, the realloc function behaves like the malloc function for
the specified size". I am not sure anything is specified if the ptr is
not NULL and the size is 0. With this patch, realloc(ptr, 0) will not
raise any warning if ptr is not NULL.
> Still, sounds like a good add. Thanks for working on this!
> On Nov 13, 2011, at 8:52, Cyril Roelandt wrote:
>> Currently, clang can check zero byte allocations for the malloc function. I think it should also warn programmers about zero byte allocations for the calloc and realloc functions.
>> Attached is a patch that implements this idea. It checks either the first argument of malloc(), or the second argument of realloc(), or both arguments of calloc(), looking for a value constrained to 0.
>> Checking both arguments of calloc() makes the code a little bit ugly, so I'll probably need to give it some more work.
>> You may find a test case attached to this mail :
>> $ clang --analyze -c -o alloc alloc.c
>> /tmp/alloc.c:29:16: warning: Call to 'malloc' has an allocation size of 0 bytes
>> int *ptr = malloc(0);
>> ^ ~
>> /tmp/alloc.c:36:16: warning: Call to 'calloc' has an allocation size of 0 bytes
>> int *ptr = calloc(0, sizeof(int));
>> ^ ~
>> /tmp/alloc.c:43:16: warning: Call to 'calloc' has an allocation size of 0 bytes
>> int *ptr = calloc(42, 0);
>> ^ ~
>> /tmp/alloc.c:50:16: warning: Call to 'realloc' has an allocation size of 0 bytes
>> int *ptr = realloc(NULL, 0);
>> ^ ~
>> Looking forward to hearing from you,
>> Cyril Roelandt.
>> cfe-commits mailing list
>> cfe-commits at cs.uiuc.edu
-------------- next part --------------
An embedded and charset-unspecified text was scrubbed...
More information about the cfe-commits