1

I have created the following program which takes user's input of an nxn array and prints it. My code has three functions namely for memory allocation for a 2D array, user data input and displaying stored data. While 1x1 to 4x4 matrix works fine, 5x5 and above matrix results in

    Segmentation fault (core dumped)

Why is it so? What am I doing wrong ? The following is my code-

#include <stdio.h>
#include <stdlib.h>

int ** allocateMemory(int, int);
void createMatrix(int **, int, int);
void displayMatrix(int **, int, int);

int main()
{
  int sizeA, sizeB;

  printf("\nMatrix type(a x b): ");
  scanf("%d %d", &sizeA, &sizeB);
  printf("You entered: %d x %d\n", sizeA, sizeB);
  int ** arrayA;

  arrayA = allocateMemory(sizeA, sizeB);
  printf("\nMATRIX A\n");
  createMatrix(arrayA, sizeA, sizeB);
  displayMatrix(arrayA, sizeA, sizeB);

  getchar();
  free(arrayA);
  printf("\n");
  return 0;
}

/*-----------------------------------------*/
/* FUNCTION TO ALLOCATE MEMORY TO AN ARRAY */
/*-----------------------------------------*/

int ** allocateMemory(int r, int c)          //r - rows, c - columns
{
  int ** ptr;
  ptr = (int **) malloc(r*sizeof(int));
  for(int i = 0; i < r; i++){
    ptr[i] = (int *) malloc(c*sizeof(int));
  }
  return ptr;
}

/*-----------------------------*/
/* FUNCTION TO CREATE A MATRIX */
/*-----------------------------*/

void createMatrix(int ** array, int r, int c)
{
  printf("\nEnter matrix values: \n");
  for(int i = 0; i < r; i++){
    for(int j = 0; j < c; j++){
      scanf("%d", &array[i][j]);
    }
  }
  printf("Array Created.");
  printf("\n");
}

/*----------------------------*/
/* FUNCTION TO DISPLAY MATRIX */
/*----------------------------*/

void displayMatrix(int ** array, int r, int c)
{
  printf("\n");
  for(int i = 0; i < r; i++){
    for(int j = 0; j < c; j++){
      printf("%5d  ", *(*(array + i) + j));
    }
    printf("\n");
  }
}
arnieM
  • 93
  • 1
  • 9
  • 1
    Have you run your program in a debugger? That is the best way to try and find the problem. At the very least it will immediately tell you exactly which line of code triggers the seg fault. And then you can trace the program execution and examine variables. [How to debug small programs](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) – kaylum Feb 20 '20 at 10:08
  • `malloc(r*sizeof(int))` --> `malloc(r*sizeof(int *))`. Or better still `malloc(r*sizeof(*ptr))` – kaylum Feb 20 '20 at 10:09
  • 1
    Voting to close as simple typo because of the `ptr = (int **) malloc(r*sizeof(int));` – Lundin Feb 20 '20 at 10:10
  • If you are running on Linux, the "valgrind" program is also very helpful for debugging these kinds of problems. – user253751 Feb 20 '20 at 10:18

1 Answers1

2

In allocateMemory() you have

ptr = (int **) malloc(r*sizeof(int));

That line is wrong, because you want t allocate memory for an array of pointers, so it shoud be

ptr = malloc(r*sizeof(int *));

or

ptr = malloc(r*sizeof *ptr);

If sizeof(int) < sizeof(int *) (as it is in general on 64bit platforms) you don't allocate enough memory which invokes Undefined Behaviour. And "Undefined" means that anything might happen, including that the codes seems to run flawlessly (at least for certain values of r and c in your case)

Off topic:

you might to want to read about why you should not cast the result of malloc()

Ingo Leonhardt
  • 9,435
  • 2
  • 24
  • 33
  • What I am thinking about is why it is working with 4 x 4 matrix though? – Eraklon Feb 20 '20 at 10:16
  • Welcome to the nature of Undefined Behaviour. I'm going to add a short sentence to the answer – Ingo Leonhardt Feb 20 '20 at 10:17
  • I understand the undefined behavior, but in a sense it defined that reproducable. So what I mean I am curious why exactly this work. I mean it can happen that maybe malloc under the hood allocates 32 byte aligned memory so this why is that even though he only requested 16 byte since his bug he still end up with valid code for 4 x 4. Note: Do not expect you to give answer for this just thinking loudly. Its a rhetorical question. – Eraklon Feb 20 '20 at 10:25
  • 1
    ... or with 4x4 you overwrite only memory that you don't access later so nothing happens, or .... I have very often experienced crashes in cases like these after some completely unrelated changes had been made to the program. Sometimes for years the bug was there but it never had any consequences – Ingo Leonhardt Feb 20 '20 at 10:30
  • @IngoLeonhardt Thanks for your help. I understood the issue. However I don't understand how come even with the bug, it worked for 4x4 matrix ? It's puzzling. – arnieM Feb 20 '20 at 10:54