0

I'm using this function to read the input matrix:

void leMatInt(int **M,int linhas,int colunas){
    int i, j;
    for (i = 0; i < linhas; i++){
      for (j = 0; j < colunas; j++){
        scanf("%d", &M[i][j]);
        //printf("Leu [%d, %d]\n", i, j);
      }
    }
}

And I'm creating the matrix like this:

scanf("%d", &v1);
int **matriz1=(int **)malloc(v1 * sizeof(int));
for(i = 0;i < v1; i++){
    matriz1[i] = (int *)malloc(v1 * sizeof(int));
}
leMatInt(matriz1, v1, v1);

The code works nicely for v1 <= 4, but if I try to input a 5v5 matrix, the code gets runtime error at the function.

Mikael
  • 482
  • 8
  • 23

3 Answers3

3

matriz1 is a double pointer so while allocating memory you should write sizeof(int*). because ** pointer will holds/contains * single pointers.

int **matriz1 = malloc(v1 * sizeof(int*));
for(i = 0;i < v1; i++){
    matriz1[i] = malloc(v1 * sizeof(int));
}

typecasting malloc() is discouraged.

Achal
  • 11,821
  • 2
  • 15
  • 37
2
int **matriz1=malloc(v1 * sizeof(int*));

A double (**) pointer variable will hold pointer to an int.

matriz1 is a pointer to a pointer variable (pointer to a int*).

So it will contain int* variables.

Also casting the return type of malloc is unnecessary and check the return value of malloc.

It's undefined behavior here. That's why it works for 4 unexpectedly but doesn't work for 5x5 matrices.


An example: (Considering a particular case)-

Though sizeof int is implementation defined, but it's usually 4 bytes. But sizeof pointer is usually 8 byte in 64-bit compiler.

Now to hold 5 int* variable you need 40 byte. But you are allocating 20 bytes. So you are allocating less memory than what you need. And accessing memory that you are not permitted to, invoking undefined behavior.

user2736738
  • 30,591
  • 5
  • 42
  • 56
0
int **matriz1=(int **)malloc(v1 * sizeof(int));

This line is wrong. As already stated by other answers, the elements pointed to by matriz1 are not integers but pointers to integers, so using sizeof with a type name should be sizeof(int *) here.

Also, casting the return value of malloc() is unnecessary and arguably bad style in C.

To avoid errors like that, sizeof can also take an expression as an operand and uses the type this expression would evaluate to, which comes very handy with malloc() -- it should look like this:

int **matriz1 = malloc(v1 * sizeof *matriz1);

If you change the type of matriz1 later, sizeof *matriz1 still gives the correct element size -- it's the size of whatever matriz1 points to.