Skip to main content

IAR Embedded Workbench for RISC-V 3.40

MEM-malloc-sizeof-ptr

In this section:
Synopsis

malloc(sizeof(p)), where p is a pointer type, is assigned to a non-pointer variable.

Enabled by default

Yes

Severity/Certainty

High/Low

highlow.png
Full description

The argument given to malloc() is the size of a pointer, but the use of the return address does not suggest a double-indirection pointer. Allocating memory to an int*, for example, should use sizeof(int) rather than sizeof(int*). Otherwise, the memory allocated might be smaller than expected, potentially leading to an application crash or corruption of other heap memory. This check is identical to CERT-MEM35-C_a.

Coding standards
CERT EXP01-C

Do not take the size of a pointer to determine the size of the pointed-to type

CERT ARR01-C

Do not apply the sizeof operator to a pointer when taking the size of an array

CWE 467

Use of sizeof() on a Pointer Type

Code examples

The following code example fails the check and will give a warning:

#include <stdlib.h>
void example(void) {
  int *p = (int*)malloc(sizeof(p)); //sizeof pointer
}

The following code example passes the check and will not give a warning about this issue:

#include <stdlib.h>
void example(void) {
  int *p = (int*)malloc(sizeof(*p));
}