Marsh_mellow
Marsh_mellow

Reputation: 1

can someone tell what's wrong with this code,it gets terminates instantly on execution

the given code is trying to initialise matrix using using pointer for dynamic memory allocation

int main()
{

    int **a;
    *a=new int[3];
    for(int i=0;i<3;i++)
    {
        a[i]=new int[3];
        a[i]=0;
    }
    cout<<"Enter 3x3 Matrix : "; 
    for(int i=0;i<3;i++)
    {
        for(int j=0;j<3;j++)
        {
            cin>>a[i][j];   
        }
    }
    //display matrix
    for(int i=0;i<3;i++)
    {
        for(int j=0;j<3;j++)
        {
            cout<<a[i][j]<<" "; 
        }
        cout<<"\n";
    }
    for(int i=0;i<3;i++)
    delete a[i];
    delete []a;
    return 0;
}

just getting terminate instantly on execution without taking any input...

Upvotes: 0

Views: 56

Answers (1)

Matheus Jahnke
Matheus Jahnke

Reputation: 31

The line *a=new int[3]; might cause the program to crash.

As a is not initialized, attempting to write to *a is undefined behavior(UB).

One way of solving this is by writing a = new int[3], but this will not compile because a is int **(a pointer to pointer to int), and not int *. One way of appeasing the compiler is by making a = new int*[3], this will allocate a pointer to an array of 3 pointers to integer.

After that, there is another thing that makes the code fail:

On the line a[i]=new int[3]; you assign a value of a newly allocated array of integers to a[i], that is fine, but then you write a[i]=0;, this changes the pointers to a NULL value, so the code fail when you try to write to a[i][j].

(I believe) You might want to initialize the allocated array to 0. On that case, you should do another for that sets each a[i][j] to 0.

There's also an subtle issue when you free the array. I believe you expect a[i] to be a pointer to an array, so you should use delete[] a[i] instead of delete a[i]. Using the wrong delete([] or not) also is UB.

Upvotes: 2

Related Questions