WG 14 Document: N 2010
Date: 2016-03-01
A call to a standard memory allocation function taking a size integer argument n and presumed to be intended for type T * shall be diagnosed when n < sizeof(T).with
A call to a standard memory allocation function taking a size integer argument n and presumed to be intended for type T * shall be regarded as an array of N elements, where N = n / sizeof(T).In rule 5.21, replaceAny allocation where N == 0 shall be diagnosed (i.e. where n < sizeof(T)). Also, any attempt to use this array in a manner that causes its array bound to be violated shall be diagnosed.
EXAMPLE In this noncompliant example, a diagnostic is required because the value of n that is used in the malloc() call has been possibly miscalculated.
wchar_t *f1(void) {
const wchar_t *p = L"Hello, World!";
const size_t n = sizeof(p) * (wcslen(p) + 1);
wchar_t *q = (wchar_t *)malloc(n); // diagnostic required
/* ... */
return q;
}
with
EXAMPLE 1
struct S1 {
unsigned int x;
float y;
struct S1 *z;
};
struct S1 *f1(void) {
struct S1 *p = (struct S1*)malloc(sizeof(p)); // diagnostic required
return p;
}
EXAMPLE 2
wchar_t *f2(void) {
const wchar_t *p = L"Hello, World!";
const size_t n = (wcslen(p) + 1);
wchar_t *q = (wchar_t *)malloc(n);
wcscpy(q, p); // diagnostic required
return q;
}