0

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");
  }

}
lurker
  • 56,987
  • 9
  • 69
  • 103
Sbpro
  • 948
  • 14
  • 27
  • `main()` hasn't been valid C since 1999. – melpomene Jun 01 '19 at 20:02
  • 4
    `p = malloc(sizeof(int) * M);` is a type error. You're allocating `M` integers, but you're trying to use `M` pointers. – melpomene Jun 01 '19 at 20:04
  • Oh yes- that should have been like so: `p = malloc(sizeof(int *) * M);` right? @melpomene – Sbpro Jun 01 '19 at 20:07
  • Yes, but preferably `p = malloc(M * sizeof *p);` because then you don't have to worry about getting the types right. And if you use `p = calloc(M, sizeof *p);`, you don't have to worry about integer overflow in the multiplication. – melpomene Jun 01 '19 at 20:10
  • Thanks @melpomene for pointing out my type error. Greatly appreciate your time and the tips! *Strangely with the system pause in the code, the program was working till end the with no issues each time I tested it. That created more confusion on me about what could be wrong. – Sbpro Jun 01 '19 at 20:19

0 Answers0