C++ 代码中未初始化的指针
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5870038/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Uninitialized pointers in code
提问by munish
I am learning C++ and I came to know that pointers if left uninitialized could point to random locations in memory and create problems that memory might be used by some other program.
我正在学习 C++ 并且我开始知道如果未初始化的指针可能指向内存中的随机位置并产生一些其他程序可能使用内存的问题。
Now if that is the case we should never have this line in any part of our code:
现在,如果是这种情况,我们不应该在代码的任何部分中包含这一行:
int* ptr;
Instead we should have something like
相反,我们应该有类似的东西
int* ptr = NULL; //Is this going to avoid the problem
Please suggest because I have seen the first line(int* ptr;
) in many books so I am getting this doubt. If possible give some examples also.
请提出建议,因为我int* ptr;
在许多书中看到了第一行(),所以我对此产生了怀疑。如果可能的话,也举一些例子。
回答by Doug T.
int* ptr = NULL; //Is this going to avoid the problem
This will cause ptr
to point to NULL
which you can explicitly check for as a default/uninitialized value. It prevents the problem you describe, but a careless programmer can still accidentally dereference a null pointer without checking, causing undefined behaviour.
这将导致ptr
指向NULL
您可以明确检查的默认/未初始化值。它可以防止您描述的问题,但是粗心的程序员仍然可以在不检查的情况下意外取消引用空指针,从而导致未定义的行为。
The main advantage is your convenience for checking whether the ptr
has or has not been initialized to anything, ie:
主要优点是您可以方便地检查是否ptr
已初始化为任何内容,即:
if (ptr != NULL)
{
// assume it points to something
}
Since this is pretty idiomatic, its pretty dangerous to not initialize the pointer to NULL
. The pointer would be initialized to a non-NULL garbage value that doesn't really point to anything real. Worst of all, the check above would pass, causing even worse problems if it just so happens that the address in the pointer is memory you can legally access. In some Embedded environments, you might be able to access any part of memory, so you might accidentally corrupt random parts of memory or random parts of your executing code.
由于这是非常惯用的,因此不将指针初始化为NULL
. 指针将被初始化为一个非 NULL 垃圾值,它并不真正指向任何真实的东西。最糟糕的是,上面的检查会通过,如果碰巧指针中的地址是您可以合法访问的内存,则会导致更严重的问题。在某些嵌入式环境中,您可能能够访问内存的任何部分,因此您可能会意外损坏内存的随机部分或执行代码的随机部分。
回答by jalf
Always initialize your variables.
始终初始化您的变量。
Occasionally, you may want to initialize to NULL
, but most of the time, you should be able to initialize the pointer to the value it is supposed to hold. Declare variables as late as possible, and initialize them at that point, not 15 lines further down in your code.
有时,您可能希望初始化为NULL
,但大多数情况下,您应该能够将指针初始化为它应该保存的值。尽可能晚地声明变量,并在那时初始化它们,而不是在代码中进一步向下 15 行。
回答by DataGraham
The line:
线路:
int* ptr;
is definitely not guaranteed to initialize the pointer value to anything in particular. The line:
绝对不能保证将指针值初始化为任何特别的东西。线路:
int* ptr = NULL;
Will initialize the pointer to point to address zero, which in practice will never hold anything useful, and which will be conventionally checked for as an invalid pointer value.
将指针初始化为指向地址零,实际上这将永远不会保存任何有用的东西,并且通常会作为无效的指针值进行检查。
Of course, it is still possible, as has been said by Doug T., to attempt to use this pointer without checking it and so it would crash all the same.
当然,正如 Doug T. 所说的那样,仍然有可能尝试使用此指针而不检查它,因此它仍然会崩溃。
Explicitly initializing to NULL has the advantage of ensuring that dereferencing the pointer before setting it to something useful will crash, which is actually a good thing, because it prevents the code from "accidentally" working while masking a serious bug.
显式初始化为 NULL 的优点是确保在将指针设置为有用的东西之前取消引用指针会崩溃,这实际上是一件好事,因为它可以防止代码在掩盖严重错误的同时“意外”工作。
回答by Heisenbug
It's alway better to initialize a pointer to NULL if for any reason you can't initialize it while declaration occurs . For example:
如果由于任何原因您无法在声明发生时初始化它,那么将指针初始化为 NULL 总是更好。例如:
Object *ptr = new Object();
Typically a function can check the value of the pointer against NULL to verify that the pointer has been initialized before. If you haven't set it explicitly to NULL, and it points to a random value, then it could be dereferenced causing a segfault.
通常,函数可以根据 NULL 检查指针的值,以验证该指针之前是否已初始化。如果您没有将它显式设置为 NULL,并且它指向一个随机值,那么它可能会被取消引用导致段错误。
回答by Jeroen Baert
If the pointer is not used, the compiler will simply ignore it. Initializing it to NULL is the safe thing to do, imho.
如果不使用指针,编译器将简单地忽略它。将其初始化为 NULL 是安全的做法,恕我直言。
Are you sure your not confusing with a function declaration? It's very common for a function to be declared as
您确定您不会与函数声明混淆吗?一个函数被声明为是很常见的
char* do_something(const char* one,const char* two);
char* do_something(const char* 一,const char* 2);
In this case, the pointers are used to specify what kind of argument you want to pass.
在这种情况下,指针用于指定要传递的参数类型。
回答by doron
C++ follow on from C in that it is not designed to be a safe; it is designed to be efficient. It is therefore for this reason that automatic variables are not initialized. It is up to you to ensure that no pointer is used before it is initialized (although many compiler will warn you if you don't initialize your variables)
C++ 继承了 C,因为它不是为了安全而设计的;它旨在高效。因此,没有初始化自动变量。由您来确保在初始化之前没有使用任何指针(尽管如果您不初始化变量,许多编译器会警告您)
回答by Shubhay
int a,*ptr;
now
现在
print(ptr,*ptr)
In the above code two cases can be possible:
在上面的代码中,可能有两种情况:
It'll execute if default value in ptr is not the address of some used memory of program.
Output:
ptr *ptr eg. 0x400730 -1992206795
It'll give error (segmental fault) if default address in the ptr is the address of some used memory of program. E.g. if the address of variable a in the memory is also 0x400730.
如果 ptr 中的默认值不是程序某些已用内存的地址,它将执行。
输出:
ptr *ptr eg. 0x400730 -1992206795
如果 ptr 中的默认地址是程序的某个已用内存的地址,则会出错(段错误)。例如,如果变量 a 在内存中的地址也是 0x400730。
回答by Jan Hudec
In C++, you should generally avoid plain old pointers altogether. Standard library classes, smart pointers (until C++0x only in various libraries like Boost or Loki) and references can and should be used in most places instead.
在 C++ 中,您通常应该完全避免使用普通的旧指针。标准库类、智能指针(直到 C++0x 仅在 Boost 或 Loki 等各种库中)和引用可以而且应该在大多数地方使用。
If you can't avoid pointers, it's indeed preferable to declare them with initializations, which in most cases should not be NULL, but the actual target value, because in C++ you can mix declarations and expressions freely, so you can and should only declare the variable at the point you have meaningful value for it.
如果不能避免指针,确实最好用初始化来声明它们,在大多数情况下不应该是NULL,而是实际的目标值,因为在C++中你可以自由地混合声明和表达式,所以你可以而且应该只声明您对它具有有意义的价值时的变量。
That's not the case with C where you have to use pointers a lot and all variables have to (or had to before C99; I am not exactly sure) be declared at the begining of a scope. So many people still have bad habits from C that are not appropriate for C++.
C 的情况并非如此,您必须大量使用指针并且所有变量都必须(或必须在 C99 之前;我不确定)在作用域的开头声明。所以很多人仍然有不适合 C++ 的 C 的坏习惯。