Main Content

Wrong type used in sizeof

sizeof argument does not match pointed type

Description

This defect occurs when both of the following conditions hold:

  1. You assign the address of a block of memory to a pointer, or transfer data between two blocks of memory. The assignment or copy uses the sizeof operator.

    For instance, you initialize a pointer using malloc(sizeof(type)) or copy data between two addresses using memcpy(destination_ptr, source_ptr, sizeof(type)).

  2. You use an incorrect type as argument of the sizeof operator. For instance:

    • You might be using the pointer type instead of the type that the pointer points to. For example, to initialize a type* pointer, you might be using malloc(sizeof(type*)) instead of malloc(sizeof(type)).

    • You might be using a completely unrelated type as sizeof argument. For example, to initialize a type* pointer, you might be using malloc(sizeof(anotherType)).

Risk

Irrespective of what type stands for, the expression sizeof(type*) always returns a fixed size. The size returned is the pointer size on your platform in bytes. The appearance of sizeof(type*) often indicates an unintended usage. The error can cause allocation of a memory block that is much smaller than what you need and lead to weaknesses such as buffer overflows.

For instance, assume that structType is a structure with ten int variables. If you initialize a structType* pointer using malloc(sizeof(structType*)) on a 32-bit platform, the pointer is assigned a memory block of four bytes. However, to be allocated completely for one structType variable, the structType* pointer must point to a memory block of sizeof(structType) = 10 * sizeof(int) bytes. The required size is much greater than the actual allocated size of four bytes.

Fix

To initialize a type* pointer, replace sizeof(type*) in your pointer initialization expression with sizeof(type).

Examples

expand all

#include <stdlib.h>

void test_case_1(void) {
    char* str;

    str = (char*)malloc(sizeof(char*) * 5);
    free(str);

}

In this example, memory is allocated for the character pointer str using a malloc of five char pointers. However, str is a pointer to a character, not a pointer to a character pointer. Therefore the sizeof argument, char*, is incorrect.

Correction — Match Pointer Type to sizeof Argument

One possible correction is to match the argument to the pointer type. In this example, str is a character pointer, therefore the argument must also be a character.

#include <stdlib.h>

void test_case_1(void) {
    char* str;

    str = (char*)malloc(sizeof(char) * 5);
    free(str);

}

Result Information

Group: Programming
Language: C | C++
Default: On for handwritten code, off for generated code
Command-Line Syntax: PTR_SIZEOF_MISMATCH
Impact: High

Version History

Introduced in R2013b

expand all