"If a C++ pointer is deleted twice, it can cause a trap" -- 陷阱是什么意思?

"If a C++ pointer is deleted twice, it can cause a trap" -- what does trap mean?

遇到这样一个C++小测验:一个指针被删除两次会怎样?

答案是D

我有点迷茫,"trap"是什么意思?它是 C++ 中的一个特殊术语吗?

直接引用the Wikipedia article on traps:

In computing and operating systems, a trap, also known as an exception or a fault, is typically[NB 1][1] a type of synchronous interrupt typically caused by an exceptional condition (e.g., breakpoint, division by zero, invalid memory access). A trap usually results in a switch to kernel mode, wherein the operating system performs some action before returning control to the originating process. A trap in a system process is more serious than a trap in a user process, and in some systems is fatal. In some usages, the term trap refers specifically to an interrupt intended to initiate a context switch to a monitor program or debugger.

这是高度概括的术语,不是由 C++ 定义的,更不用说特定于它了。更关键的是,你一定要注意选择题中的"can",因为不能保证你双删一个对象时任何事情都会发生[=13] =]

其实四个答案基本上说的是同一个东西

无论如何,测验似乎很混乱,因为 "deleting a pointer" 可能不是它的意思。

不要与 SNMP 陷阱混淆:

In SNMP, a trap is a type of PDU used to report an alert or other asynchronous event about a managed subsystem.

它在 C++ 中没有任何意义。这可能意味着操作系统级别的错误(例如 Posix 信号),但没有上下文我不能说。

正确答案是它会导致未定义的行为;但是所有的答案都可以被认为是正确的,因为未定义的行为可能会导致这些事情发生。

删除已经删除的相同内存是未定义的行为。任何事情都可能发生,尽管就我而言,它给出了运行时错误。使用 g++ 4.9.1

在 C++ 中编译

我的程序:

int main()
{
    int x = 5;
    int *ptr = &x;
    delete ptr;
    delete ptr;
}

它给出了以下错误:

*** Error in `./t': free(): invalid pointer: 0xbf971994 ***