为什么MISRA C状态指针的副本可能会导致内存异常? [英] Why does MISRA C state that a copy of pointers can cause a memory exception?

查看:170
本文介绍了为什么MISRA C状态指针的副本可能会导致内存异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

MISRA C 2012指令4.12就是动态内存分配不应该使用。

MISRA C 2012 directive 4.12 is "Dynamic memory allocation should not be used".

作为一个例子,该文件提供$ C $的c此示例:

As an example, the document provides this sample of code:

char *p = (char *) malloc(10);
char *q;

free(p);
q = p; /* Undefined behaviour - value of p is indeterminate */

和文件指出:

虽然存储在指针的值不变继
  呼叫释放,这是可能的,在某些目标,该存储器
  它指向的不再存在的和复制的行为该指针
  可能会导致内存异常

Although the value stored in the pointer is unchanged following the call to free, it is possible, on some targets, that the memory to which it points no longer exists and the act of copying that pointer could cause a memory exception.

我确定几乎所有的判决,但最后。由于p和q都在堆栈上分配,指针的副本是如何导致内存异常?

I'm ok with almost all the sentence but the end. As p and q are both allocated on the stack, how can the copy of the pointers cause a memory exception ?

推荐答案

根据标准,复制指针 Q = P:,是不确定的行为。

According to the Standard, copying the pointer q = p;, is undefined behaviour.

阅读的 J.2未定义行为的规定:

指针到一个对象,其生命周期结束时所使用的值(6.2.4)。

The value of a pointer to an object whose lifetime has ended is used (6.2.4).

将这一章我们看到:

对象6.2.4贮存持续时间

的对象的生存期是在此期间,存储程序的执行的一部分
  保证被保留它。一个对象存在,具有恒定的地址,33),并保留
  其最后的存储如果一个对象被称为以外整个lifetime.34值)其
  一生中,该行为是不确定的。 指针的值变得不确定时,
  它指向(或刚刚过去的)对象达到其生命周期的结束。

The lifetime of an object is the portion of program execution during which storage is guaranteed to be reserved for it. An object exists, has a constant address,33)and retains its last-stored value throughout its lifetime.34)If an object is referred to outside of its lifetime, the behavior is undefined. The value of a pointer becomes indeterminate when the object it points to (or just past) reaches the end of its lifetime.

什么是不确定的:

3.19.2 不确定的值的:
  无论是一个未确定的值或重新presentation陷阱

3.19.2 indeterminate value: either an unspecified value or a trap representation

这篇关于为什么MISRA C状态指针的副本可能会导致内存异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆