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

Asked

Viewed 793 times

0

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
    }
}
  • That line from if has a { without a }.

  • I forgot to put it at the time to send the question but the code is right. I’m reading a txt with 10,000 names, when I have it report generated from 1918

1 answer

1


Let’s see that code:

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

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

Assuming that these pointers are not all overwritten with something else, it means that when accessing if(th->vet[i]->tamanho >= 0), if the th->vet[i] produce a null pointer by ->tamanho the result will be a segmentation failure.

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

        if (th->vet[i] && th->vet[i]->tamanho >= 0) {
  • worked thanks

  • @Felipesantos If this answer solved your problem and there is no doubt left, mark it as correct/accepted by clicking on the " " that is next to it, which also marks your question as solved. If you still have any questions or would like further clarification, feel free to comment.

Browser other questions tagged

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