Foros del Web » Programación para mayores de 30 ;) » C/C++ »

[SOLUCIONADO] Segmentation fault 11, con listas enlazadas

Estas en el tema de Segmentation fault 11, con listas enlazadas en el foro de C/C++ en Foros del Web. Hola verán me he registrado porque tengo un problema que no consigo solucionar. Este programa pide al usuario introducir una matriz (usando una estructura con ...
  #1 (permalink)  
Antiguo 18/05/2015, 03:42
 
Fecha de Ingreso: mayo-2015
Mensajes: 19
Antigüedad: 8 años, 11 meses
Puntos: 0
Exclamación Segmentation fault 11, con listas enlazadas

Hola verán me he registrado porque tengo un problema que no consigo solucionar.
Este programa pide al usuario introducir una matriz (usando una estructura con campo puntero a puntero), y después pide introducir un numero de fila. La fila introducida se va metiendo, elemento a elemento, en un nodo de una nueva lista enlazada, algo así:

Código:
Matriz:
(1 2 3)
(4 5 6) -----> selecciono fila 1
(7 8 9)

-Entonces: 
Lista enlazada:
raiz -> [4] -> [5] -> [6] -> NULL 
La matriz se crea bien, y se muestra bien.
El error está en la función de extraerFilaLiberarMatriz, se llama así pero aun no he hecho la parte de liberar la matriz jeje. Alguna sugerencia? He depurado y el error puede ser que me falta "allocar" algo en memoria pero no se qué...

Código:
//

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

typedef int * intRef;
typedef struct matInt {
    int **m;
    int numFil, numCol;
} matInt;
typedef matInt* matIntRef;


typedef int tipoInfo;
typedef tipoInfo *tipoInfoRef;

typedef struct tipoNodo {
    tipoInfo info;
    struct tipoNodo * sig;
} tipoNodo;

typedef tipoNodo *tipoNodoRef;
typedef tipoNodo * ListaEnlazada;
typedef ListaEnlazada *ListaEnlazadaRef;

ListaEnlazadaRef extraerFilaLiberarMatriz(matIntRef matriz, int nFila);
int leerMatInt(matIntRef );
matIntRef crearMatInt(int numFil, int numCol, intRef errNum);
int mostrarMatInt(matIntRef);



int main (int argc, const char * argv[]) {
    int i;
    int f, c, fila_a_lista, errNum;
    matIntRef mat;
    ListaEnlazadaRef lista = NULL;
    tipoNodoRef indice = NULL;
    
    printf("\n\nDimensiones de las matrices:\n\n");
    printf("Numero filas: ");
    scanf("%d", &f);
    printf("\nNumero columnas: ");
    scanf("%d", &c);
    
    printf("Introducir valores Matriz: \n");
    if (NULL != (mat = crearMatInt(f, c, &errNum)))
        leerMatInt(mat);
    else
        printf("Fallo creación matriz: %d\n",errNum);

    printf("Introducir FILA a extraer: \n");
    scanf("%d", &fila_a_lista);
    
    mostrarMatInt(mat);
    
    if((lista = extraerFilaLiberarMatriz(mat, fila_a_lista)) == NULL)
        printf("Fallo extraer fila\n");
    indice = *lista;
    while (indice != NULL) {
        printf("- %d - ", indice->info);
        indice = indice -> sig;
    }
    
    return 0;
}

ListaEnlazadaRef extraerFilaLiberarMatriz(matIntRef matriz, int nFila) {
    int i;
    ListaEnlazadaRef raiz = NULL;
    tipoNodoRef nuevo = NULL, aux = NULL;
    printf("LLEGO");
    for (i=0; i<(matriz->numCol); i++) {
            nuevo = (tipoNodoRef) malloc(sizeof(tipoNodo));
            nuevo->info = matriz->m[nFila][i];
            nuevo->sig = NULL;
            aux = *raiz;
            
            if (aux == NULL) {
                *raiz = nuevo;
            }
            else {
                while (aux -> sig != NULL) {
                    aux = aux -> sig;
                }
                aux -> sig = nuevo;
            }
        }

    return raiz;
}


matIntRef
crearMatInt(int numF, int numC, intRef errNum)
{
    matIntRef temp;
    int i;
    if (!(numF > 0 && numC > 0)) {
#ifdef DEBUG
        fprintf(stderr, "Error: dimensiones incorrectas: %d, %d\n",numF,numC);
#endif
        *errNum = -1;
        return NULL;
    }
    if (NULL == (temp = malloc(sizeof(matInt)))){
#ifdef DEBUG
        fprintf(stderr, "Error: fallo reserva memoria tipo matriz\n");
#endif
        *errNum = -2;
        return NULL;
    }
    else if (NULL == (temp->m = malloc(numF*sizeof(int *)))){
#ifdef DEBUG
        fprintf(stderr, "Error: fallo reserva memoria matriz\n");
#endif
        free(temp);
        *errNum = -3;
        return NULL;
    }
    else {
        temp->numFil = numF;
        temp->numCol = numC;
        for (i = 0; i < numF; i++) {
            if (NULL == (temp->m[i] = malloc(numC*sizeof(int)))){
                for (i--; i >= 0; i--)
                    free(temp->m[i]);
                free(temp->m);
                free(temp);
#ifdef DEBUG
                fprintf(stderr, "Error: fallor reserva memoria matriz\n");
#endif
                *errNum = -4;
                return NULL;
            }
        }
        *errNum = 0;
        return temp;
    }
}


int
leerMatInt(matIntRef mat)
{
    
    int i,j,res;

        for (i=0; i < mat->numFil; i++) {
            for (j=0; j < mat->numCol; j++) {
                printf("mat[%d][%d] = ",i,j);
                scanf("%d%*c",&(mat->m[i][j]));
                //scanf("%d%*c",(*(mat->m + i) + j));
            }
        }
        return 0;

}


int
mostrarMatInt(matIntRef matriz)
{
    int i,j;
            for (i = 0; i < matriz->numFil; i++) {
            printf("| ");
            for (j = 0; j < matriz->numCol; j++) {
                printf("%d",matriz->m[i][j]);
                //printf(c,*(*(mat->m + i) + j));
            }
            printf(" |\n");
        }
        return 0;

}
  #2 (permalink)  
Antiguo 18/05/2015, 03:49
 
Fecha de Ingreso: octubre-2014
Ubicación: Madrid
Mensajes: 1.212
Antigüedad: 9 años, 6 meses
Puntos: 204
Respuesta: Segmentation fault 11, con listas enlazadas

Código C++:
Ver original
  1. ListaEnlazadaRef extraerFilaLiberarMatriz(matIntRef matriz, int nFila) {
  2.   ListaEnlazadaRef raiz = NULL;
  3.   for (i=0; i<(matriz->numCol); i++) {
  4.     // ...
  5.     aux = *raiz;
  6.            
  7.     if (aux == NULL)
  8.     {
  9.       *raiz = nuevo;
  10.     }
  11.     // ...
  12.   }
  13.   return raiz;
  14. }

"ListaEnlazadaRef" es un puntero... ¿dónde reservas memoria para dicho puntero? en ninguna parte. Te falta reservar memoria para este objeto

Un saludo
  #3 (permalink)  
Antiguo 18/05/2015, 03:58
 
Fecha de Ingreso: mayo-2015
Mensajes: 19
Antigüedad: 8 años, 11 meses
Puntos: 0
Respuesta: Segmentation fault 11, con listas enlazadas

Cita:
Iniciado por eferion Ver Mensaje

"ListaEnlazadaRef" es un puntero... ¿dónde reservas memoria para dicho puntero? en ninguna parte. Te falta reservar memoria para este objeto

Un saludo
"ListaEnlazadaRef" es el tipo de dato que defini con typedef, me imagino que te referirás a algún puntero como raíz o no se... Aun así no veo lo que me quieres decir, la función debe devolver solo un puntero que apunte a la lista enlazada, la reserva de memoria a esta lista ya se realiza en la función de la que hablamos.

EDITO: Gracias ya lo resolvi, si que tenia que reservar memoria para la RAIZ dentro de la función. Mil gracias!

Última edición por albondi; 18/05/2015 a las 04:20

Etiquetas: enlazadas, fault, lista, matriz
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 03:02.