gpt4 book ai didi

c - 为什么 MISRA C 声明指针的副本会导致内存异常?

转载 作者:太空狗 更新时间:2023-10-29 16:20:44 25 4
gpt4 key购买 nike

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

例如,文档提供了这个代码示例:

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都分配在栈上,指针的拷贝怎么会导致内存异常呢?

最佳答案

根据标准,复制指针 q = p; 是未定义的行为。

阅读 J.2 Undefined behavior 指出:

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

转到那一章我们看到:

6.2.4 Storage durations of objects

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

什么是不确定的:

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

关于c - 为什么 MISRA C 声明指针的副本会导致内存异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26704344/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com