1

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

1
  • 6
    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. Commented Jul 3, 2013 at 13:37

3 Answers 3

6

Here, you declare a pointer that points to nowhere in particular:

int * pointer_s3_1_a;

Here, you attempt to set the value of the thing it points to to 100:

*pointer_s3_1_a=100;

This is undefined behaviour, and could cause a segmentation violation (although it doesn't have to, many wrong things could happen, and not all as noticeable as a segmentation fault. You just got lucky).

You must first make your pointer point to somewhere valid. For example,

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
Sign up to request clarification or add additional context in comments.

Comments

2

You cannot write data to uninitialized areas of memory:

int * pointer_s3_1_a;  // NOT Initialized (possibly 0)!!!
*pointer_s3_1_a=100;   // Undefined behaviour

2 Comments

It's very unlikely to be 0, actually. And a page fault is only one possible outcome.
@LightnessRacesinOrbit OK, fixed comments.
2

you have declared pointer_s3_1_a and pointer_s3_1_a2 as pointers, but there's actually no memory to point to, as you have missed to allocate/create them. You should do:

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

...

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.