neovim/neovim — pull request #949 by splinterofchaos (2014-07-13 16:59:35+00:00)
Title: [RFC] Ensure well-defined alloc behaviour.

clang defect report [1] caught this potential bug in memory.c, line 112:

> Call to 'calloc' has an allocation size of 0 bytes

calloc(0,x) or (x,0) and malloc(0) may return a NULL or non-NULL pointer
[2] on some implementations. Set the size and/or count to at least one
before calling an alloc() function to avoid undefined behaviour.

[1] defect report:
http://ruiabreu.org/neovim-analysis/report-oLRUxF.html#Path4

[2] http://man.he.net/man3/calloc

I'm certain that no code using `xcalloc()` right now is broken. I experimentally found that gcc will zero-fill at least 24 bytes of space, even on `calloc(0,0)`, but I hope nothing actually relies on that behaviour.

```c
#include
#include

int main() {
char* p = calloc(0,0); // OOPS!

if( p == NULL ) return 1;

size_t i = 0;
for( ; p[i] == 0; i++ )
printf("char @ %zu = %i\n", (size_t)p + i, (int)p[i]);
printf("char @ %zu = %i\n", (size_t)p, (int)p[i]);

free(p);
return 0;
}
```
Tested with:
```bash
$ gcc alloc.c
$ ./a.out | wc --lines
25
```