Matrix in dynamic allocation with execution failure

0

Hello

The following code has compiled but has an error executing:

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

typedef struct 
{
    char *nome;
    int valor;
    int peso;
} objeto;

objeto obj[] = {
    {"map",      10,   2},
    {"compass",   7,   1},
    {"water",    25,   6},
    {"tin",      24,   5},
};

 // max{ f(Xn-1, W-Pn) + Vn , f(Xn-1, W) }    

int solver(objeto *obj, int n, int capac )
{
    int i, j, taDentro, taFora;
    int **matriz = (int **) calloc(n+1, sizeof(int *));

    matriz[0] = (int *) calloc(capac+1, sizeof(int)); 
    for (i=1; i<=n; i++) 
    {
        matriz[i] = (int *) calloc(capac+1, sizeof(int));

        for (j=1; j<=capac; j++)
        {
            taFora = matriz[i-1][j]; //coloca o item anterior?
            if (obj[i-1].peso > matriz[i][j]) matriz[i][j] = taFora;
            // -1 pq os itens em 'matriz' comecam em 1 
            else
            {
              taDentro = matriz[i-1][ j-obj[i].peso ] + obj[i].valor;
              if (taDentro > taFora) matriz[i][j] = taDentro;
              else                   matriz[i][j] = taFora;
            }
        }
    }
    int resultado;
    resultado = matriz[i][j];

    for (i = 0; i < n; i++) free(matriz[i]);
    free(matriz);
    return resultado;
}

int main()
{
    int n = 3;
    int capac = 7;
    int resultado;
    resultado = solver(obj, n, capac);
    printf("%d\n", resultado);
}

The windows window shows this information:

Problem Event Name: APPCRASH

I do not know if I'm trying to write or read information in the wrong space, or if I'm using the pointers in the wrong way. Or both.

Sirs, could you help me?

    
asked by anonymous 18.06.2016 / 05:06

2 answers

1

I recommend that you use GDB to debug your program if you can not solve the problem.

According to the debugger, the segmentation fault occurs on the following line:

resultado = matriz[i][j];

Variable values after segmentation failure:

i = 4

j = 8

capac = 7

n = 3

What we can notice is that:

The following loop:

for (i=1; i<=n; i++) 

The variable i starts at 1, the loop rotates while i is less than or equal to 3 (value of n), so far so good, but watch out for the i

18.06.2016 / 17:50
0

I think the problem lies in this line:

resultado = matriz[i][j];

Because at this point% w / w will be% w / w% and w / w w w w w w w w w w w w w w w w w w w w w w w w w w w w w w w w w w w w w w w w w w w w w w w w w w w w w w w w w w w w w w w     

18.06.2016 / 16:41