Using the following struct:
typedef struct lista {
int num;
struct lista * sig;
} nodo;
We then have the following function to erase a linked list formed by the previous struct nodes:
void eliminarListaEntera(nodo * registro) {
nodo * aux = NULL;
while(registro->sig != NULL){
aux=registro->sig;
printf("Borrando nodo de la lista\n");
free(registro);
registro=aux;
}
free(registro);
registro = NULL;
}
The issue I'm seeing: If I run the following inside main() before and after calling eliminarListaEntera:
printf("POINTER %p\n", (void *) primerNodo);
I get the same value. Shouldn't it be 0 (NULL) after calling the delete function?
If I try to traverse it again, I get only a random value like -159426562 which I guess it's because it's retrieving a garbage value from memory.
CodePudding user response:
When main
calls eliminarListaEntera(primerNodo)
, it passes the value of primerNodo
. Inside eliminarListaEntera
, the parameter registro
is a separate object and does not refer in any way to the primerNodo
in main
.
The statement registro = NULL;
sets registro
to NULL
and has no effect on primerNodo
in main
.
If you want a called function to affect an object in the caller, you can pass a pointer to the object:
void eliminarListaEntera(nodo **p) {
nodo *registro = *p; // Copy the original pointer for ease of use.
nodo * aux = NULL;
while(registro->sig != NULL){
aux=registro->sig;
printf("Borrando nodo de la lista\n");
free(registro);
registro=aux;
}
free(registro);
*p = NULL; // Set the original pointer to NULL.
}
Then main
can call this routine with eliminarListaEntera(&primerNodo);
.