主要内容

本页采用了机器翻译。点击此处可查看最新英文版本。

MISRA C:2012 Rule 18.6

The address of an object with automatic or thread-local storage shall not be copied to another object that persists after the first object has ceased to exist

描述

规则定义

The address of an object with automatic or thread-local storage shall not be copied to another object that persists after the first object has ceased to exist 1 .

理由

当对象的生命周期到期时,该对象的地址将变得不确定。使用不确定的地址会导致未定义行为。

Polyspace 实现

当指向局部变量的指针离开该变量的作用域时,Polyspace® 会报告违反此规则。例如:

  • 函数返回一个指向局部变量的指针。

  • 函数执行赋值 globPtr = &locVarglobPtr 是全局指针变量,locVar 是局部变量。

  • 函数执行赋值 *paramPtr = &locVarparamPtr 是函数参数,例如 int** 指针,locVar 是局部变量 int

Polyspace 将此规则应用于使用 alloca 函数分配的内存,并忽略静态局部变量。Polyspace 假定函数定义中的局部对象位于同一范围内。

故障排除

如果您预期会出现违规,但未看到该违规,请参阅诊断为何编码规范违规未按预期显示

示例

全部展开


void func2(int *ptr) {
    *ptr = 0;
}

int* func1(void) {
    int ret = 0; //Noncompliant
    return &ret ;
}
void main(void) {
    int* ptr = func1() ;
    func2(ptr) ;
}

在此示例中,func1 返回指向局部变量 ret 的指针。

main 中,ptr 指向本地变量的地址。当在 func2 中访问 ptr 时,该访问是非法的,因为 ret 的作用域仅限于 func1

char *func(void) {
	char local_auto; /* Noncompliant*/
	return &local_auto ;  /* &local_auto is indeterminate*/
}

在此示例中,由于 local_auto 是局部变量,因此函数返回后,local_auto 的地址不确定。Polyspace 报告了违规。


void h(void){
    static unsigned short *q;
    
    unsigned short x =0u; //Noncompliant
    q = &x;  
}

在此示例中,函数 h 将本地变量 x 的地址存储在静态变量 q 中。静态变量 q 的生命周期在局部变量 x 的生命周期结束后仍然存在。将 x 复制到 q 不合规,并且 Polyspace 标记了变量 x

在此示例中,线程局部变量 thread_local_var 的地址被赋值给全局指针 ptr_global_var。然后在线程 myThread 上调用函数 thread_function。在 myThread 终止后,变量 thread_local_var 脱离作用域,指针 ptr_global_var 指向已销毁的对象。Polyspace 报告违反此规则。

#include <stdint.h>
#include <threads.h>
#include <stdlib.h>

_Thread_local int32_t thread_local_var = 0;
int* ptr_global_var;

void* thread_function(void* arg) {
    thread_local_var = (int32_t)arg;
    ptr_global_var = &thread_local_var;         /* Noncompliant */
}

void call_thread_function(void) {
    thrd_t myThread;

    ptr_global_var = &thread_local_var;
    thrd_create(&myThread, thread_function, (void*)1L);
    thrd_join(myThread, NULL);

    *ptr_global_var = 2; /* Bad memory access */
}

检查信息

组:指针和数组
类别:必需
AGC 类别:必需

版本历史记录

全部展开


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.