Reputation: 37
I am trying to implement a 2D array using dynamic memory allocation. Here is my code:
#include <iostream>
using namespace std;
int main()
{
int r, c;
cin >> r >> c;
int** p = new int*[r];
for (int i = 0; i < r; i++)
{
p[i] = new int[c]; //this line here is the marked line
}
for (int i = 0; i < r; i++)
{
for (int j = 0;j <c; j++)
{ cin >> p[i][j];
}
}
for (int i = 0; i < r; i++)
{
for (int j = 0;j <c; j++)
{
cout << p[i][j]<<" ";
}
}
cout<<"\n";
for (int i = 0; i < r; i++)
{
delete [] p[i];
}
delete [] p;
return 0;
}
I then compiled the same code by commenting the marked line in different compilers.
VS Code with MinGW (MinGW.org GCC-6.3.0-1) -> Compiled successfully with all the wanted output.
Jdoodle and other online compilers (tried in both c++14 and c++17 latest versions) -> The program gives segmentation fault after reading the second input for array element (reads the r, c and first 2 input for the array succesfully).
Could someone please explain, IN VS CODE, how am I getting the correct output? Which memory, heap or stack is used if marked line is commented? What are the differences when the marked line is commented and when not commented? And what's the reason of Segmentation fault? Thanks.
Upvotes: 1
Views: 159
Reputation: 310980
In general the program has undefined behavior.
In this for loop
for (int i = 0; i < r; i++)
{
p[i] = new int[i + 1]; //this line here is the marked line
}
in each "row" of the array you allocated i + 1
elements. But in the next for loop (and in subsequent loops)
for (int i = 0; i < r; i++)
{
for (int j = 0;j <c; j++)
{ cin >> p[i][j];
}
}
you are trying to access c
elements in each row independent on how many elements actually were allocated. So if c
is greater than 1 then at least in the first iteration of the loop there is an attempt to access a memory beyond the allocated array.
Edit: If you commented this line
p[i] = new int[c]; //this line here is the marked line
as you wrote
I then compiled the same code by commenting the marked line in different compilers.
then again the program has undefined behavior. That is you are using uninitialized pointers. It means that anything can occur.
Upvotes: 1