C ++ SegFault,当解除引用cout的指针时 [英] C++ SegFault when dereferencing a pointer for cout
问题描述
我是C ++的新手,只是试图搞定它。它通常似乎不太糟糕,但我偶然发现了这种奇怪的/病理性的错误行为:
I'm new to C++ and just trying to get a hang of it. It generally seems not too bad, but I stumbled upon this weird/pathological segfaulting behavior:
int main () {
int* b;
*b = 27;
int c = *b;
cout << "c points to " << c << endl; //OK
printf( "b points to %d\n", *b); //OK
// cout << "b points to " << (*b) << endl; - Not OK: segfaults!
return 0;
}
这个程序产生了你期望的结果:
This program, as given, produces what you'd expect:
c points to 27
b points to 27
另一方面,如果你取消第二行到最后一行的注释,你会得到一个程序在运行时崩溃(seg-fault)。为什么?这是一个有效的指针。
On the other hand, if you uncomment the second-to-last line, you get a program that crashes (seg-fault) in runtime. Why? This is a valid pointer.
推荐答案
int * b
指向未知的内存地址,初始化。如果你把它初始化为你的编译器存在的任何空值(C ++中为0或NULL,C ++ 0x中为nullptr),你最好能早一些获得segfault。问题在于你为指针分配空间,而不是它指向的数据。如果您改为这样做:
int* b
points to an unknown memory address because it wasn't initialized. If you initialized it to whatever null value exists for your compiler (0 or NULL in C++, nullptr in C++0x), you'd most certainly get a segfault earlier. The problem lies in the fact that you allocated space for the pointer but not the data it points to. If you instead did this:
int c = 27;
int* b = &c;
cout << "c points to " << c << endl;
printf ("b points to %d\n", *b);
cout << "b points to " << (*b) << endl;
事情会工作,因为 int * b
到您的程序可访问的内存位置(因为内存实际上是您的程序的一部分)。
Things would work because int* b
refers to a memory location that is accessible by your program (since the memory is actually a part of your program).
如果您保留一个指针未初始化或分配空值它,你不能使用它,直到它指向一个内存地址,你知道你可以访问。例如,使用动态分配与 new
运算符将为您保留数据的内存:
If you leave a pointer uninitialized or assign a null value to it, you can't use it until it points to a memory address that you KNOW you can access. For example, using dynamic allocation with the new
operator will reserve memory for the data for you:
int* b = new int();
*b = 27;
int c = *b;
//output
delete b;
这篇关于C ++ SegFault,当解除引用cout的指针时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!