Main Content

MISRA C:2012 Rule 19.1

An object shall not be assigned or copied to an overlapping object

Description

Rule Definition

An object shall not be assigned or copied to an overlapping object1 .

Rationale

When you assign an object to another object with overlapping memory, the behavior is undefined. The exceptions are:

  • You assign an object to another object with exactly overlapping memory and compatible type.

  • You copy one object to another using memmove.

Additional Message in Report

  • An object shall not be assigned or copied to an overlapping object.

  • Destination and source of XX overlap, the behavior is undefined.

Troubleshooting

If you expect a rule violation but do not see it, refer to Diagnose Why Coding Standard Violations Do Not Appear as Expected.

Examples

expand all

void func (void) {
    union {
        short i;
        int j;
    } a = {0}, b = {1};
    
    a.j = a.i;   /* Non-compliant */
    a = b;       /* Compliant */
}

In this example, the rule is violated when a.i is assigned to a.j because the two variables have overlapping regions of memory.

#include <string.h>

int arr[10];

void func(void) {
    memcpy (&arr[5], &arr[4], 2u * sizeof(arr[0]));    /* Non-compliant */
    memcpy (&arr[5], &arr[4], sizeof(arr[0]));         /* Compliant */
    memcpy (&arr[1], &arr[4], 2u * sizeof(arr[0]));    /* Compliant */
}

In this example, memory equal to twice sizeof(arr[0]) is the memory space taken up by two array elements. If that memory space begins from &a[4] and &a[5], the two memory regions overlap. The rule is violated when the memcpy function is used to copy the contents of these two overlapping memory regions.

typedef struct
{
    char init_string[21];
    char new_string[101];
} string_aggr;


string_aggr my_string_aggr;

void copy()
{
    strncpy(&my_string_aggr.new_string[0], /* Non-compliant */
            &my_string_aggr.init_string[0], 100U);  
}

In this example, the member init_string of the aggregate structure my_string_aggr consists of 21 characters. But, more than 21 characters of this member are copied to the adjoining member new_string, resulting in an overlapping copy.

Check Information

Group: Overlapping Storage
Category: Mandatory
AGC Category: Mandatory

Version History

Introduced in R2014b

expand all


1 All MISRA coding rules and directives are © Copyright The MISRA Consortium Limited 2021.

The MISRA coding standards referenced in the Polyspace® Bug Finder™ documentation are from the following MISRA standards:

  • MISRA C:2004

  • MISRA C:2012

  • MISRA C:2023

  • MISRA C++:2008

  • MISRA C++:2023

MISRA and MISRA C are registered trademarks of The MISRA Consortium Limited 2021.