Problem in the use of malloc and realloc

Asked

Viewed 447 times

2

int main()
{
    int **matriz;

    f(matriz);

    return 0;
}

void f(int **matriz)
{
    int x, l=1,c=3;

    matriz = (int **) malloc(sizeof (int));
    *matriz = (int *) malloc(3 * sizeof (int));

    printf("Insira o valor de x: ");
    scanf("%d", &x);

    if(x==0)
    {
        c*=2;
        *(matriz) = (int *) realloc(*(matriz),c * sizeof (int));
    }
    else
    {
        l++
        matriz = (int **) realloc(matriz, l* sizeof (int));
        *(matriz) = (int *) malloc(3 * sizeof (int));
    }
}

Good, I leave here an example of the problem I have had in the implementation of malloc and realloc, basically I start by adding a row and 3 columns to insert certain values later in the first condition I continue to insert in the first row, but in the second condition I already want the values in another row and more 3 columns, this kind of implementation always ends up giving me memory error and I do not know how to find the error, if anyone could help thank.

  • But the idea was to ask for more values to insert the numbers in other rows and/or columns ? It’s just that I see one scanf function. How you are testing/checking the values you get?

  • basically what I’ve got to do

  • Probably not explained well my problem, the code I put is just an example of the code I have had problems, basically it is a realloc(): invalid next size and it was to know if this format as I put on top has some error, I basically do matrix = (int *) realloc(matrix, l sizeof (int)); to add new row and *(matrix+i) = (int *) malloc(n * sizeof (int)); to add more columns, where might the error be coming from? Another thing I saw is the use of NULL initialization that I do not use, it is important this use?

3 answers

1

I start by responding to some of the things you put in the comments:

Another thing I’ve seen is using the NULL boot that I don’t use

In some cases it becomes necessary, when the code tests if certain thing comes to NULL, in others serves as good practice. In your example you could have declared the matrix with initial value a NULL, which would even solve one of the compilation warnings:

int main()
{
    int **matriz = NULL;
    f(matriz); 
    ...
}

Although not necessary for the logic you have, it makes it clear what value you start with. When you do f(matriz) is passing a copy of the pointer that has in main what causes the allocation within the function f do not change this pointer, which is incorrect.

Look at this question that I answered exactly with the same problem and its solution

the code I put in is just an example of the code I’ve been getting problems

The example he set is a bit obscure, and difficult to decipher what he was supposed to do (not even because it has an expected result), so it is difficult to help in his real doubt. It would have been better to have put a portion of your actual code.

i basically make matrix = (int *) realloc(matrix, l sizeof (int)); to add new line

If matriz is a int** and l is the new size, which has already been increased by 1 somewhere, so it would be:

matriz = (int**) realloc(matriz, l * sizeof (int*));

and *(matrix+i) = (int *) malloc(n * sizeof (int)); to add more columns

Assuming n is the number of columns each row is right, but simpler would be to do:

matriz[i] = (int *) malloc(n * sizeof (int));

Passing the code itself

When does:

*matriz = (int *) malloc(3 * sizeof (int));

Although it works is a little strange, and later the same principle is used incorrectly. In this statement you want to assign to the first line an array of 3 integer, that would be the columns. Make this clearer by making:

matriz[0] = (int *) malloc(3 * sizeof (int));

Hence the realloc who is right is the penultimate :

else
{
    l++
    //-^ falta ;

    matriz = (int **) realloc(matriz, l* sizeof (int)); //<--correto
    *(matriz) = (int *) malloc(3 * sizeof (int)); //<--incorreto
}

The last one should be:

matriz[l-1] = (int *) malloc(3 * sizeof (int));

Or if you want to use pointer notation, as you were using:

*(matriz+l-1)  = (int *) malloc(3 * sizeof (int));

Distinct example with dynamic row and column creation

Here’s a different example with dynamic row and column creation of an array and reallocation to more rows, as I was trying to do. I made a different example to be more intuitive and clear, and just focus on the part that you want to know.

int main()
{
    int linhas = 2, colunas = 5, i;
    int **matriz = (int **) malloc(sizeof (int*) * linhas); //cria as linhas

    //cria as colunas em cada linha
    for (i = 0; i < linhas; ++i){
        matriz[i] = (int*)malloc(sizeof (int) * colunas);
    }

    //coloca alguns valores e mostra
    matriz[0][1] = 10; 
    matriz[1][3] = 10;
    mostrarMatriz(matriz, linhas, colunas);

    //cria uma nova linha
    matriz = (int**) realloc(matriz, sizeof(int*) * ++linhas);

    //cria as colunas para essa nova linha
    matriz[linhas-1] = (int*)malloc(sizeof (int) * colunas);

    //atribui um valor na nova linha e volta a mostrar o resultado
    matriz[linhas-1][0] = 5;
    mostrarMatriz(matriz, linhas, colunas);

    return 0;
}

See the result in Ideone

Note that I left uninitialized values in the array to simplify the code. In Ideone are appearing as zeros, but it is not guaranteed to be so, so it would be good practice to assign values throughout the matrix.

0

here an example using columns and rows map. c

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

char** mapa;
int linhas;
int colunas;

void liberamapa(){
    for (int i = 0; i < linhas; ++i)
    {
        free(mapa[i]);
    }
    free(mapa);
}
void alocamapa(){
    mapa = malloc(sizeof(char*) * linhas);
    for (int i = 0; i < linhas; ++i)
    {       
        mapa[i] = malloc(sizeof(char) * (colunas +1));
    }
}
void lemapa(){
        FILE* f;

    f = fopen("mapa.txt", "r");
    if(f == 0) {
        printf("Erro na leitura do mapa");
        exit(1);
    }

    fscanf(f, "%d %d", &linhas, &colunas);
    alocamapa();

    for(int i = 0; i < 5; i++) {
        fscanf(f, "%s", mapa[i]);
    }
    fclose(f);
}
int main() {

    lemapa();


    for(int i = 0; i < 5; i++) {
        printf("%s\n", mapa[i]);
    }

    liberamapa();

}

matriz = malloc(sizeof(int*)* linhas);
for (int i = 0; i < linhas; ++i)
{       
    matriz[i] = malloc(sizeof(int) * colunas);
}

file. h

void liberamapa();
void alocamapa();
void lemapa();

map

|--------|
|...|..-.|
|..-|.@..|
|......-.|
|--------|

0

The code posted has several problems, which I explain below.

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

static void f(int **matriz);

int main()
{
  int **matriz;

  // nao faz sentido passar um ponteiro nao inicializado para uma funcao!
  f(matriz);
  return 0;
}

void f(int **matriz)
{
  int x, l = 1, c = 3;

  // matriz = (int **) malloc(sizeof (int)); // <-------- ERRO
  matriz = (int **) malloc(sizeof (int*));   // tem que alocar "int*", nao "int"
  // neste ponto matriz[0] existe, mas aponta para "lixo"

  *matriz = (int *) malloc(3 * sizeof (int));
  // neste ponto existem
  // matriz[0][0]
  // matriz[0][1]
  // matriz[0][2]
  // mas nao sabemos qual seu conteudo

  printf("Insira o valor de x: ");
  scanf("%d", &x);

  if (x == 0)
  {
    c *= 2;
    *(matriz) = (int *) realloc(*(matriz),c * sizeof (int));
    // neste ponto existem
    // matriz[0][0]
    // matriz[0][1]
    // matriz[0][2]
    // matriz[0][3]
    // matriz[0][4]
    // matriz[0][5]
    // mas nao sabemos qual seu conteudo
  }
  else
  {
    // l++ // <------------------------ ERRO faltando ;
    l++;
    matriz = (int **) realloc(matriz, l* sizeof (int));
    // neste ponto existem
    // matriz[0][0]
    // matriz[0][1]
    // matriz[0][2]
    // matriz[1]    <--- novo ponteiro
    // mas nao sabemos qual seu conteudo

    // *(matriz) = (int *) malloc(3 * sizeof (int));
    // esta' realocando *matriz, que e' equivalente a matriz[0], mas como esta'
    // realocando para um mesmo tamanho, provavelmente nada vai ser realocado!

    // o correto é fazer o malloc de *(matriz+1), equivalente a matriz[1]
    *(matriz+1) = (int *) malloc(3 * sizeof (int));
    // neste ponto existem
    // matriz[0][0]
    // matriz[0][1]
    // matriz[0][2]
    // matriz[1][0]
    // matriz[1][1]
    // matriz[0][2]
    // mas nao sabemos qual seu conteudo
  }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.