2

我正在尝试学习 C++ 中指针算法的一些操作。下面编写的代码向我抛出了分段错误。我无法理解程序如何尝试访问未分配的内存以导致分段错误。

C++ 代码( myarray.cc )

#include<iostream>
using namespace std;

int main(int argc, char** argv)
{
  int * pointer_s3_1_a;
  int * pointer_s3_1_a2;
  int value_s3_1_a, value_s3_1_a2 ;

  *pointer_s3_1_a=100;
  cout<<"pointer_s3_1_a, *pointer_s3_1_a "<<pointer_s3_1_a<<' '<<*pointer_s3_1_a<<endl;
  value_s3_1_a=*pointer_s3_1_a++; 
  cout<<"value_s3_1_a, pointer_s3_1_a, *pointer_s3_1_a "<<
    value_s3_1_a<<' '<<pointer_s3_1_a<<' '<<*pointer_s3_1_a<<endl;

  cout<<"pointer_s3_1_a2, *pointer_s3_1_a2 "<<pointer_s3_1_a2<<' '<<*pointer_s3_1_a2<<endl;

  *pointer_s3_1_a2=100; //Runtime error |** Segmentation fault (core dumped) **|

  return 0;
}

我正在使用 g++ 编译器在 Ubuntu 12.04 中运行该程序。在终端上运行apt-cache policy g++给了我以下输出。

g++:已安装:4:4.6.3-1ubuntu5 候选:4:4.6.3-1ubuntu5
版本表: * 4:4.6.3-1ubuntu5 0 500 http://archive.ubuntu.com/ubuntu/precision/main i386 包100 /var/lib/dpkg/状态

4

3 回答 3

7

在这里,您声明了一个特别指向任何地方的指针:

int * pointer_s3_1_a;

在这里,您尝试将它指向的事物的值设置为100

*pointer_s3_1_a=100;

这是未定义的行为,可能会导致分段违规(尽管不是必须的,但可能会发生许多错误的事情,而且并不像分段错误一样明显。你很幸运)。

您必须首先使您的指针指向某个有效的地方。例如,

int n = 42;
pointer_s3_1_a = &n; // pointer points to n
*pointer_s3_1_a=100; // set the value of the thing it points to (n) to 100
于 2013-07-03T13:38:54.880 回答
2

您不能将数据写入未初始化的内存区域:

int * pointer_s3_1_a;  // NOT Initialized (possibly 0)!!!
*pointer_s3_1_a=100;   // Undefined behaviour
于 2013-07-03T13:39:45.877 回答
2

您已将 pointer_s3_1_a 和 pointer_s3_1_a2 声明为指针,但实际上没有可指向的内存,因为您错过了分配/创建它们。你应该做:

int* pointer_s3_1_a = new int();
*pointer_s3_1_a = 100;

...

int* pointer_s3_1_a2 = new int();
*pointer_s3_1_a2 = 100;
于 2013-07-03T13:44:38.943 回答