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?

5
  • Please do not upload images of code/errors when asking a question. Commented Oct 27, 2021 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. Commented Oct 27, 2021 at 14:58
  • 2
    []OT *(p+i*c+j) might be p[i * c + j]. Commented Oct 27, 2021 at 14:58
  • Off-topic, but recommended reading: Why is "using namespace std;" considered bad practice? Commented Oct 27, 2021 at 15:09
  • Also off-topic, but std::unique_ptr<int[]> p = std::make_unique<int[]>(r * c) is preferable if your compiler supports it. See here and here. Commented Oct 28, 2021 at 15:14

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

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.