How to check if the list is empty or with an element in C

1
typedef struct {
    int tamanho;
    nodo *inicio;
} lista;

typedef struct {
    lista **vet;
    int tamTabHash;
    int colisoes;
} tabHash; 

tabHash *criaTabelaHash(int tamanho){
    if(tamanho < 1) return NULL;
    tabHash* hash = (tabHash*)malloc(sizeof(tabHash));
    hash->tamTabHash = tamanho;
    hash->colisoes = 0;  
    hash->vet = (lista**)calloc(tamanho, sizeof(lista*));
    return hash;
}

void gerarRelatorioHash(tabHash *th) {
    int i;

    int listocupada = 0, listvazia = 0;

    for (i = 0; i < th->tamTabHash ; i++) {
        if(th->vet[i]->tamanho >= 0) { // essa linha me da falha de segmentacao
    }
}
    
asked by anonymous 04.07.2018 / 03:13

1 answer

1

Let's look at this code:

    hash->vet = (lista**)calloc(tamanho, sizeof(lista*));

The hash->vet will point to a memory area that contains a number of initially null pointers. This quantity is given by tamanho .

Assuming that these pointers are not all overwritten with something else, this means that when accessing if(th->vet[i]->tamanho >= 0) , if th->vet[i] produces a null pointer, doing ->tamanho will result in a segmentation fault. / p>

To know which solution is best, you would need to provide more information about the context in which the criaTabelaHash and gerarRelatorioHash functions are used. However, assuming that it is actually possible for th->vet[i] to be null, a possible solution would be to change if to look like this:

        if (th->vet[i] && th->vet[i]->tamanho >= 0) {
    
04.07.2018 / 03:23