I am working on a small library where I don't want to deal with allocation errors everywhere they might pop up, so I've written a wrapper around malloc()
that terminates the program (for now) if an error occurs.
void *cstr_malloc(size_t size)
{
void *buf = malloc(size);
if (!buf)
{
fprintf(stderr, "Allocation error, terminating\n");
exit(2);
}
return buf;
}
Nothing fancy there. Now, however, I noticed that the clang static analyzer, in Xcode at least, doesn't catch obvious leaks that it would have done before.
If I do something like this:
void foo(void)
{
void *p = malloc(100);
}
it would naturally inform me that p
would likely leak memory.
However, with
void foo(void)
{
void *p = malloc(100);
void *q = cstr_malloc(100);
}
it only reports that p
, but not q
, is leaking.
That makes sense; it can't know everywhere the program might allocate memory and still analyse it in a reasonable time. It handles my allocator fine if I inline it, so there it can see it, but otherwise, it doesn't.
Is there any way to tell the analyser that I have a function that returns freshly allocated memory? Some attribute, like __attribute__((malloc))
or similar?
I can, of course, just inline the function, but I have a bunch of other functions that similarly allocate memory, and it would be problematic to inline all of them.
p
, not the (equally allocated)q
. It doesn't see (and here, of course, can't see) thatq
is also allocated memory.p
, but the code highlight under it is onq
. Confusing stuff.