Skip to main content

IAR Embedded Workbench for RL78 5.20

CERT-EXP33-C_b

In this section:
Synopsis

Do not read uninitialized memory.

Enabled by default

Yes

Severity/Certainty

High/Medium

highmedium.png
Full description

Uninitialized automatic variables or dynamically allocated memory has indeterminate values, which for objects of some types, can be a trap representation. Reading such trap representations is undefined behavior; it can cause a program to behave in an unexpected manner and provide an avenue for attack.

Coding standards
CERT EXP33-C

Do not reference uninitialized memory

CWE 758

Reliance on Undefined, Unspecified, or Implementation-Defined Behavior

CWE 824

Access of Uninitialized Pointer

CWE 908

Use of Uninitialized Resource

Code examples

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

#include <stdlib.h>
#include <stdio.h>
enum { OLD_SIZE = 10, NEW_SIZE = 20 };

int *resize_array(int *array, size_t count) {
    if (0 == count) {
        return 0;
    }

    int *ret = (int *)realloc(array, count * sizeof(int));
    if (!ret) {
        free(array);
        return 0;
    }

    return ret;
}

void func(void) {

    int *array = (int *)malloc(OLD_SIZE * sizeof(int));
    if (0 == array) {
        /* Handle error */
    }

    for (size_t i = 0; i < OLD_SIZE; ++i) {
        array[i] = i;
    }

    array = resize_array(array, NEW_SIZE);
    if (0 == array) {
        /* Handle error */
    }

    for (size_t i = 0; i < NEW_SIZE; ++i) {
        printf("%d ", array[i]);
    }
}

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

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

enum { OLD_SIZE = 10, NEW_SIZE = 20 };

int *resize_array(int *array, size_t old_count, size_t new_count) {
    if (0 == new_count) {
        return 0;
    }

    int *ret = (int *)realloc(array, new_count * sizeof(int));
    if (!ret) {
        free(array);
        return 0;
    }

    if (new_count > old_count) {
        memset(ret + old_count, 0, (new_count - old_count) * sizeof(int));
    }

    return ret;
}

void func(void) {

    int *array = (int *)malloc(OLD_SIZE * sizeof(int));
    if (0 == array) {
        /* Handle error */
    }

    for (size_t i = 0; i < OLD_SIZE; ++i) {
        array[i] = i;
    }

    array = resize_array(array, OLD_SIZE, NEW_SIZE);
    if (0 == array) {
        /* Handle error */
    }

    for (size_t i = 0; i < NEW_SIZE; ++i) {
        printf("%d ", array[i]);
    }
}