Main Content

Hard-coded buffer size

Size of memory buffer is a numerical value instead of symbolic constant

Description

This defect occurs when you use a numerical value instead of a symbolic constant when declaring a memory buffer such as an array.

Risk

Hard-coded buffer size causes the following issues:

  • Hard-coded buffer size increases the likelihood of mistakes and therefore maintenance costs. If a policy change requires developers to change the buffer size, they must change every occurrence of the buffer size in the code.

  • Hard-constant constants can be exposed to attack if the code is disclosed.

Fix

Use a symbolic name instead of a hard-coded constant for buffer size. Symbolic names include const-qualified variables, enum constants, or macros.

enum constants are recommended.

  • Macros are replaced by their constant values after preprocessing. Therefore, they can expose the loop boundary.

  • enum constants are known at compilation time. Therefore, compilers can optimize the loops more efficiently.

    const-qualified variables are usually known at run time.

Examples

expand all

int table[100];

void read(int);

void func(void) {
    for (int i=0; i<100; i++)
        read(table[i]);
}

In this example, the size of the array table is hard-coded.

Correction — Use Symbolic Name

One possible correction is to replace the hard-coded size with a symbolic name.

const int MAX_1 = 100;        
#define MAX_2 100
enum { MAX_3 = 100 };

int table_1[MAX_1];
int table_2[MAX_2];
int table_3[MAX_3];

void read(int);

void func(void) {
    for (int i=0; i < MAX_1; i++)
        read(table_1[i]);
    for (int i=0; i < MAX_2; i++)
        read(table_2[i]);
    for (int i=0; i < MAX_3; i++)
        read(table_3[i]);
}

Result Information

Group: Good practice
Language: C | C++
Default: Off
Command-Line Syntax: HARD_CODED_BUFFER_SIZE
Impact: Low

Version History

Introduced in R2015b