Clang: strange malloc usage

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

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.