Is that piece of code redundant?

Asked

Viewed 114 times

0

I recently did a C proof in which I had to complete a code to remove items from a queue, follow the code with the answer considered correct highlighted:

typedef struct No {
  int dado;
  struct No *proximo;
};

typedef struct Fila {
  struct No *inicio;
  struct No *fim;
}; 

struct Fila *filaDePosts;

int filaRemover(){
 struct No* ptr_no = fila->inicio;
 int dado;

 if (ptr_no != NULL) {
    **fila->inicio = ptr_no->proximo;**
    **ptr_no->proximo = NULL;**
    dado = ptr_no->dado;
    free(ptr_no);
    return dado;
 }
}

In the code snippet ptr_no->proximo = NULL;, whereas just below I execute the command free(ptr_no); which will already release the memory allocated to the struct ptr_no and its internal variables, it is redundant and unnecessary to cancel the value?

1 answer

1


Yes, it seems redundant, it is changing a data that is not used later in an object that will soon be destroyed.

Taking advantage could have declared dado direct in its use and would have a less redundant code. And could have used a type in the typedef to avoid the redundancy of using struct.

typedef struct no {
    int dado;
    struct no *proximo;
} No;

typedef struct {
    No *inicio;
    No *fim;
} Fila;

I put in the Github for future reference.

In the code also no longer need to use struct.

Browser other questions tagged

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