cxong / tinydir

Lightweight, portable and easy to integrate C directory and file reader

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

clang-tidy warning (tinydir.h:366) Call to 'malloc' has an allocation size of 0

wojdyr opened this issue · comments

It's about a clang-tidy warning. It can be reproduced on tinydir samples, see below. I didn't analyze the flow so I'm not sure if it's a false positive. If it is a false positive, would it be ok to add a NOLINT comment to silence it?

$ /local/clang+llvm-5.0.0-linux-x86_64-ubuntu16.04/bin/clang-tidy samples/random_access_sample.c -- -I.
9 warnings generated.
./tinydir.h:366:32: warning: Call to 'malloc' has an allocation size of 0 bytes [clang-analyzer-unix.API]
        dir->_files = (tinydir_file *)_TINYDIR_MALLOC(sizeof *dir->_files * n_files);
                                      ^
./tinydir.h:175:33: note: expanded from macro '_TINYDIR_MALLOC'
        #define _TINYDIR_MALLOC(_size) malloc(_size)
                                       ^
/home/wojdyr/fresh/tinydir/samples/random_access_sample.c:8:32: note: Assuming 'argc' is < 2
        if (tinydir_open_sorted(&dir, argc >= 2 ? argv[1] : ".") == -1)
                                      ^
/home/wojdyr/fresh/tinydir/samples/random_access_sample.c:8:32: note: '?' condition is false
/home/wojdyr/fresh/tinydir/samples/random_access_sample.c:8:6: note: Calling 'tinydir_open_sorted'
        if (tinydir_open_sorted(&dir, argc >= 2 ? argv[1] : ".") == -1)
            ^
./tinydir.h:346:2: note: Taking false branch
        if (tinydir_open(dir, path) == -1)
        ^
./tinydir.h:350:2: note: Loop condition is false. Execution continues on line 358
        while (dir->has_next)
        ^
./tinydir.h:360:2: note: Taking false branch
        if (tinydir_open(dir, path) == -1)
        ^
./tinydir.h:366:32: note: Call to 'malloc' has an allocation size of 0 bytes
        dir->_files = (tinydir_file *)_TINYDIR_MALLOC(sizeof *dir->_files * n_files);
                                      ^
./tinydir.h:175:33: note: expanded from macro '_TINYDIR_MALLOC'
        #define _TINYDIR_MALLOC(_size) malloc(_size)
commented

I guess this does catch a potential bug - if n_files was 0 and the platform doesn't return NULL for malloc(0), the code will continue past the NULL check, and if for some reason there are now files in the folder, it could read data into an invalid address. There should be a n_files == 0 check and bail before https://github.com/cxong/tinydir/blob/master/tinydir.h#L374 so we don't rely on the assumption that malloc(0) returns NULL.