1

I was playing with pointers and clases here i got stuck.Please help....

#include <iostream>
#define len 10

using namespace std;

class test{
private:
  int *ar;

public:
  test();
  void foo();
};

test :: test(){
  int arr[len];
  for (int i =0 ; i < len; i++){
    cin>>arr[i];
  }
  this->ar = arr;
}

void test::foo(){
  for(int i = 0;i<len;i++)
    cout<<this->ar[i]<<endl;
}

int main() {
  test ob;
  ob.foo();
  return 0;
}

when im running the code i get this ouput..

[uzumaki@uzumaki-pc C_pros]$ ./a.out 
1 2 3 4 5 6 7 8 9 10
1
0
810691180
21880
5
6
1713156944
32767
9
10  

i expected the output should come
1
2
3
4
5
6
7
8
9
10

Please explain ...Thank you...

  • 1
    `arr` is local to `test::test()`, and after that routine ends it goes out of scope. The pointer which refers to it then refers to garbage. – Eljay Mar 12 '18 at 00:25
  • 1
    You attempt to print content of a temporary variable. – Killzone Kid Mar 12 '18 at 00:25
  • 1
    If you did more investigation (why aren't there more investigative, new C++ programmers?), you would have seen that calling `foo` right after you assigned, like this: `this->ar = arr; foo();` would have given you the correct results. So then you should have seen that there is something different about calling `foo()` after the function returns. – PaulMcKenzie Mar 12 '18 at 00:28

1 Answers1

4

Array that you have declared in the constructor has local scope. When the constructor finishes it's execution the local array will get destroyed. Assigning it's address to a pointer will cause undefined behaviour when the pointer is used elsewhere. You should use dynamic memory allocation for such purposes. You should also take care of the deletion of ar pointer.

You could try this in the constructor

test :: test(){
  this->ar = new int[len];
  for (int i =0 ; i < len; i++){
    cin>>ar[i];
  }
}

And add this in the destructor

test :: ~ test(){
   if(this->ar != NULL)
   {
      delete[] this->ar;
   }
}
AstroMax
  • 112
  • 9
  • Following the "rule of three" -- because you implement a destructor, it's likely that you should also implement a copy constructor and copy-assignment operator. In this case, you must do so because if you ever pass a `test` to a function, it will be copied -- and the copy will be destructed at the end of the function, freeing the memory right out from under the original instance. When it itself is destructed, the memory will be freed *again*, which is UB. It is always a little cumbersome for this reason to allocate memory inside of a class without smart pointers. Use smart pointers. :) – jcarpenter2 Mar 12 '18 at 00:37
  • @UzumakiSaptarshi • since you are doing C++, you should use new/delete (if you need to use them at all, since there are often better alternatives in C++). malloc/calloc are more suited for C. – Eljay Mar 12 '18 at 00:45
  • Do read this [SO post](https://stackoverflow.com/questions/184537/in-what-cases-do-i-use-malloc-vs-new) – AstroMax Mar 12 '18 at 00:51