I'm trying to learn some manupulations of pointer arithmetics in C++. The code written below throws me a Segmentation Fault. I could not comprehend how the program tries to access unallocated memory to cause a segmentation fault.
C++ Code (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;
}
I'm running the program in Ubuntu 12.04 with g++ compiler. Running apt-cache policy g++ on terminal gave me the following output.
g++: Installed: 4:4.6.3-1ubuntu5 Candidate: 4:4.6.3-1ubuntu5
Version table: * 4:4.6.3-1ubuntu5 0 500 http://archive.ubuntu.com/ubuntu/ precise/main i386 Packages 100 /var/lib/dpkg/status
int * pointer_s3_1_a;...*pointer_s3_1_a=100;is UB. Please PLEASE learn C++ using a book. Don't throw code in and expect it to work.