I am studying C and I am encountering an issue with a program I am writing for practicing purposes.
In this program: I create a dynamic two-dimensional table (array) by allocating memory after the user sets the rows and columns of the table.
However the program will execute till the end, only if the table's rows are set to a very low value e.g. up 2-3 rows max.
Setting a higher number of rows will result in the program exiting.
The only way to see the program running through the end and where it finally prints the values of the table is to pause the execution early (like you can see in the code below pasted below).
Is there any explanation for this behavior? Is there anything that I am missing or doing it wrongly?
main()
{
int **p;
int i, j, N, M;
printf("Set Table Rows: ");
scanf("%d", &M);
printf("Set Table Columns: ");
scanf("%d", &N);
p = malloc(sizeof(int) * M);
system("echo \"Press any button to continue\"");
system("read");
if (!p)
{
printf("Memory Allocation Failed!");
exit(0);
}
for (i = 0; i < M; i++)
{
p[i] = malloc(sizeof(int) *N);
if (!p[i])
{
printf("Memory Allocation Failed!");
exit(0);
}
}
for (i = 0; i < M; i++)
{
for (j = 0; j < N; j++)
{
p[i][j] = (i+2) * (j+1);
}
}
printf("\n-------------------\n");
for (i = 0; i < M; i++)
{
for (j = 0; j < N; j++)
{
printf("%d\t",p[i][j]);
}
printf("\n");
}
}