[LLVMdev] Clang: strange malloc usage

mats petersson mats at planetcatfish.com
Wed Jul 29 08:34:16 PDT 2015


Yes, if malloc returns NULL in either of those cases, it will (probably,
depending on architecture) crash. Are you actually seeing cases where this
happens?

"Fixing" this is hard, since it's pretty much just going to end up with `if
it's NULL exit with a message of out of memory`, and I'm not sure you want
that either...

There are probably several thousand other allocations all over clang/llvm
where the result is not checked from malloc/new, because basically the
assumption is that allocating memory always works.

Note that at least in linux, because the OS allows "overcommit", it's
nearly impossible to write a meaningful program that runs out of memory and
gets NULL back from malloc - it gets killed by OOM-killer before it gets to
the point of returning NULL from malloc - I haven't tried in Windows for a
long time.

--
Mats

On 29 July 2015 at 16:16, Valery Pushkar <pollnossa at gmail.com> wrote:

> Hello everyone!
>
> I've found weird lines of code in tools/libclang/CIndex.cpp file in clang
> sources. Function clang_tokenize holds the following lines:
>
>   *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
>   memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
>
> Since malloc function can return null pointer and there are no checks for
> this case, memmove invocation leads to segmentation fault.
>
> The same case can be found in tools/libclang/CXString.cpp file in
> function createDup:
>
>   char *Spelling = static_cast<char *>(malloc(String.size() + 1));
>   memmove(Spelling, String.data(), String.size());
>
>
> Could somebody clarify me if I'm wrong?
>
> Thanks,
> Valeriy
>
>
> _______________________________________________
> LLVM Developers mailing list
> LLVMdev at cs.uiuc.edu         http://llvm.cs.uiuc.edu
> http://lists.cs.uiuc.edu/mailman/listinfo/llvmdev
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.llvm.org/pipermail/llvm-dev/attachments/20150729/b9eeb380/attachment.html>


More information about the llvm-dev mailing list