在没有new的情况下为指针赋值

Assigning value to pointer without new

根据我对 C++ 的基本了解,我假设以下代码会出现 运行 次错误。因为编译器没有为y指针分配任何space,我应该在给y指针赋值之前添加y = new int;

我错了还是编译器隐式为 y 指针分配了 space? (我用 Dev-C++ 4.9.9.2 编译了我的代码。)

#include <cstdlib>
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{   
    int* x;
    int* y;               
    x = new int;          
    *x = 42;              
    cout << *x << "\n";   
    *y = 13;              
    cout << *y << "\n";   
}

第 4.1 节指出:

An lvalue (3.10) of a non-function, non-array type T can be converted to an rvalue. If T is an incomplete type, a program that necessitates this conversion is ill-formed. If the object to which the lvalue refers is not an object of type T and is not an object of a type derived from T, or if the object is uninitialized, a program that necessitates this conversion has undefined behavior. If T is a non-class type, the type of the rvalue is the cv-unqualified version of T. Otherwise, the type of the rvalue is T.

未定义意味着任何事情都有可能发生——无法保证。

来自维基Making pointers safer

A pointer which does not have any address assigned to it is called a wild pointer. Any attempt to use such uninitialized pointers can cause unexpected behavior, either because the initial value is not a valid address, or because using it may damage other parts of the program. The result is often a segmentation fault, storage violation or wild branch (if used as a function pointer or branch address).

Am I wrong or compiler has allocate space for y pointer implicitly?

没有,这样的赋值是未定义的行为。这意味着它可以长时间工作并且不会引起任何问题,但突然会使您的应用程序崩溃。变量 y 实际上被分配了一些随机值,*y=13; 将 13 分配给了一些随机内存地址,它可以是某个结构或堆栈的有效内存地址。如果您最初将 y 初始化为 nullptr(或 0、NULL)int* y=nullptr;,那么您应该会遇到应用程序崩溃。