0
#include<cstdio>
#include<string>
#include<iostream>

using namespace std; 

int main()
{
        int a[]={0,1,2,3};
        int *r[]={NULL};

        for(int i=0;i<4;i++)
        {
                r[i]=&a[i];
                cout << &a[i] << endl;
                cout << a[i]<<endl;
        }

        for(int i=0;i<4;i++)
        {
                cout << r[i] << endl;
                cout << *r[i] << endl;
        }
        return 0;
}

I have started working on the array of pointers very recently. Can someone please help me out in finding the mistake in the above program..

I attached the screenshots of the results when run on windows and linux platforms.

On Windows,the addresses of the *r[] and a[] are matching and still the values are not matching.

On linux,it says "BUS ERROR" sometimes and "Segmentation fault" sometimes.

It would be better if someone explain what the "BUS ERROR" mean? And why does it come for this program. linux GCC

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
starkk92
  • 5,754
  • 9
  • 43
  • 59

4 Answers4

6

Your array r only has space for a single element in it, but you store 4. That overwrites memory, causing the crash.

Change this:

int *r[]={NULL};

to:

int *r[sizeof a / sizeof *a];

This makes r have the same number of elements as a, in other words 4.

unwind
  • 391,730
  • 64
  • 469
  • 606
  • Would it be a good idea to create a community-wiki question, something like "I'm writing to indexes outside the array bounds, why is my program crashing/hanging/giving wrong results?", so we can then mark these types of questions as duplicates and point them to it? – sashoalm Sep 09 '13 at 08:11
  • @sashoalm, I'm sure we have a few. – chris Sep 09 '13 at 13:31
  • I searched, but I couldn't find any. – sashoalm Sep 09 '13 at 13:58
3

int *r[]={NULL}; should be int *r[]={0, 0, 0, 0};

That will allocates space for four pointers that your following code need.

BUS ERROR: What is a bus error?

Community
  • 1
  • 1
lulyon
  • 6,707
  • 7
  • 32
  • 49
3

Your are not allocating enough space for your r. Try int *r[4]; and you will not get a segmentation fault.

int *r[] = {0} it's equivalent with int *r[1];

Silent Control
  • 614
  • 10
  • 22
0

r is an array of pointers, but in your code, it has only one element. You are lucky to run it on windows but it's a undefined behavior. It might seem to work today, on your compiler, but it is not legal C or C++, and there is no guarantee that it'll still work the next time you run the program. Or that it hasn't overwritten essential data even now, and you just haven't encountered the problems that is going to cause yet.

jfly
  • 7,715
  • 3
  • 35
  • 65