[PATCH] added option to detect malloc(0) as error with ASAN

Dominique Pellé dominique.pelle at gmail.com
Sat Mar 15 13:29:37 PDT 2014


Attached is a patch to detect call of malloc with size 0 as an
error with ASAN. Calling malloc(0) is admittedly not necessarily
incorrect, so the check is disabled by default and can be enabled
by adding 'detect_malloc_zero=1' to the environment variable
ASAN_OPTIONS. Behavior of malloc(0) depends on platforms:
it returns an address on most platforms but returns NULL at
least on AIX. So calling malloc(0) is a source of portability bugs.

This is my fist clang patch and I'm not sure whether the patch is
the best way to do that. Perhaps it would be better if UBSAN
detected it rather than ASAN.

Here is an example to illustrate:

$ cat test-malloc0.cpp

#include <cstdlib>
#include <cstdio>

int main(int argc, char *argv[])
  char *c = (char *)malloc(atoi(argv[1]));
  if (c == NULL) {
    fprintf(stderr, "Failed to allocate\n");
    return -1;
  return 0;

$ clang++ --fsanitize=address
$ ./a.out 0
(no error reported by default, option needs to be enabled in ASAN_OPTIONS)

$ export ASAN_OPTIONS=detect_malloc_zero=1
$ ./a.out 0
==7999==ERROR: malloc with 0 size is platform dependent
    #0 0x46d52b in malloc
    #1 0x488314 in main (/home/pel/sb/a.out+0x488314)
    #2 0x7ffd07136de4 in __libc_start_main


-------------- next part --------------
A non-text attachment was scrubbed...
Name: asan-malloc-size-0.patch
Type: text/x-diff
Size: 4995 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/llvm-commits/attachments/20140315/5509bd62/attachment.patch>

More information about the llvm-commits mailing list