I am trying to stop integer overflow vulnerabilities by creating a simple wrapper around malloc(3)
and related functions. The idea is that it returns a NULL
pointer if the amount of required memory is too large for the size_t
argument (or zero). However my implementation does not seem to be satisfying our static analyzer. Can anyone identify what is wrong with this implementation?
template <typename T>
T* safe_malloc(const size_t num_elements)
{
if (num_elements <= 0 || num_elements > SIZE_MAX / sizeof(T))
{
return NULL;
}
return static_cast<T*>(malloc(sizeof(T) * num_elements));
}
Usage:
// Previously:
int *a = (int*)malloc(sizeof(int)); // single value
int *b = (int*)malloc(sizeof(int) * ATTACKER_CONTROLLED_VALUE); // array
if (b == NULL) {
// out of memory
}
// Now:
int *a = safe_malloc<int>(1); // single value
int *b = safe_malloc<int>(ATTACKER_CONTROLLED_VALUE); // array
if (b == NULL) {
// out of memory OR user provided value that would overflow, or zero
}