0

Code:-

    #include <iostream> 
    using namespace std;
    
    int main() {
        int r,c,*p;
        cout<<"Rows : ";
        cin>>r;
        cout<<"Columns : ";
        cin>>c;
        
        p=new int[r*c];
        
        cout<<"\nEnter array elements :"<<endl;
        int i,j,k;
        for( i=0;i<r;i++){
          for( j=0;j<c;j++){
            cin>>k;
            *(p+i*c+j)=k;
          }
        }
        
        cout<<"\nThe array elements are:"<<endl;
        for( i=0;i<r;i++){
          for( j=0;j<c;j++){
            cout<<*p<<" ";
            p=p+1;
          }
          cout<<endl;
        }
        cout<<endl;
        
        delete[]p;
        return 0; 
}

Output:-

Output

Error:-

munmap_chunk(): invalid pointer Process finished with exit code -6.

Can anyone explain why the above error occurs?

Karthik
  • 5
  • 1
  • [Please do not upload images of code/errors when asking a question.](//meta.stackoverflow.com/q/285551) – vsr Oct 27 '21 at 14:57
  • 2
    When you `delete[]p` at the end, `p` is no longer pointing to the start of the array, so what you're deleting isn't valid. – ChrisMM Oct 27 '21 at 14:58
  • 2
    []OT `*(p+i*c+j)` might be `p[i * c + j]`. – Jarod42 Oct 27 '21 at 14:58
  • Off-topic, but recommended reading: [Why is "using namespace std;" considered bad practice?](https://stackoverflow.com/q/1452721/10686048) – ChrisMM Oct 27 '21 at 15:09
  • Also off-topic, but `std::unique_ptr p = std::make_unique(r * c)` is preferable if your compiler supports it. See [here](https://en.cppreference.com/w/cpp/memory/unique_ptr) and [here](https://en.cppreference.com/w/cpp/memory/unique_ptr/make_unique). – Daniel Dearlove Oct 28 '21 at 15:14

1 Answers1

1

The problem occurs at the end of your program, when you delete[] p. In the nested for-loop immediately preceding it, you are modifying p, thus, when attempting to delete[] p at the end, you get undefined behaviour.

Potential fixes include, when printing the array elements, access the pointer the same way you did in the first for loop (or as Jarod mentioned, using [i * c + j].

Alternatively, you can use an additional variable.

int *tmp = p;
for( i = 0 ; i < r; i++ ){
   for( j = 0; j < c; j++ ){
       cout << *tmp << " ";
       tmp = tmp + 1; // ++tmp; also works
   }
   cout << endl;
}
cout << endl;
        
delete[] p;

This way, p still points to the original address.

ChrisMM
  • 8,448
  • 13
  • 29
  • 48