Skip to main content

IAR Embedded Workbench for RISC-V 3.40

CERT-MEM36-C

In this section:
Synopsis

Do not modify the alignment of objects by calling realloc().

Enabled by default

Yes

Severity/Certainty

Low/Medium

lowmedium.png
Full description

Do not invoke realloc() to modify the size of allocated objects that have stricter alignment requirements than those guaranteed by malloc(). Storage allocated by a call to the standard aligned_alloc() function, for example, can have stricter than normal alignment requirements. The C standard requires only that a pointer returned by realloc() be suitably aligned so that it may be assigned to a pointer to any type of object with a fundamental alignment requirement.

Coding standards
CERT MEM36-C

Do not modify the alignment of objects by calling realloc()

Code examples

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

#include <stdlib.h>

void func(void) {
    size_t resize = 1024;
    size_t alignment = 1 << 12;
    int *ptr;
    int *ptr1;

    if (NULL == (ptr = (int *)aligned_alloc(alignment, sizeof(int)))) {
        /* Handle error */
    }

    if (NULL == (ptr1 = (int *)realloc(ptr, resize))) {
        /* Handle error */
    }
}

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

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

void func(void) {
    size_t resize = 1024;
    size_t alignment = 1 << 12;
    int *ptr;
    int *ptr1;

    if (NULL == (ptr = (int *)aligned_alloc(alignment,
                                            sizeof(int)))) {
        /* Handle error */
    }

    if (NULL == (ptr1 = (int *)aligned_alloc(alignment,
                                             resize))) {
        /* Handle error */
    }

    if (NULL == (memcpy(ptr1, ptr, sizeof(int)))) {
        /* Handle error */
    }

    free(ptr);
}