i’m experimenting with trees and nodes and I having trouble.
I have
typedef struct nodo
{
int cuenta;
int fondo;
struct nodo *sig;
}pNodo;
typedef pNodo *tLista;
typedef struct tree
{
int RUT;
struct tree *izq;
struct tree *der;
struct nodo *tLista;
}tTree;
typedef tTree *tABB;
typedef tTree *tNodo;
void crearArbol(tABB arbol)
{
tABB nuevoA;
nuevoA=(tABB)malloc(sizeof(tTree));
arbol=nuevoA;
arbol->izq=NULL;
arbol->der=NULL;
}
int AgregarCuenta(tABB *arbol,int rut,int id_cuenta,int saldo)
{
tABB AUX;
AUX=*arbol;
tLista nuevaC;
int i=1;
if(AUX==NULL)
{
crearArbol(AUX);
if(id_cuenta==1)
{
(AUX->tLista)->fondo=saldo;
return 0;
}
else
{
return -1;
}
}
else
{
if(rut==AUX->RUT)
{
while(AUX->tLista!=NULL)
{
if(AUX->tLista->cuenta==id_cuenta)
{
return -1;
}
else
{
AUX->tLista=AUX->tLista->sig;
i++;
}
}
nuevaC=(tLista)malloc(sizeof(pNodo));
nuevaC->sig=NULL;
nuevaC->cuenta=i;
nuevaC->fondo=saldo;
AUX->tLista=nuevaC;
return 0;
}
else
{
if(rut<AUX->RUT)
{
AUX=AUX->izq;
AgregarCuenta(&AUX,rut,id_cuenta,saldo);
}
else
{
AUX=AUX->der;
AgregarCuenta(&AUX,rut,id_cuenta,saldo);
}
}
}
}
int main()
{
tABB arbolillo;
crearArbol(arbolillo);
AgregarCuenta(&arbolillo, 18020200, 1, 9999);
return 0;
}
It dies on “(AUX->tLista)->fondo=saldo;” at the AgregarCuenta function. with “EXC_BAD_ACCESS”
What am I doing wrong?
I believe
crearArbolrequires a pointer to a pointer as input:And the call:
Otherwise, you don’t ‘return’ the value to the calling code.
Additionally, just after that you have:
But if you’ve just called
crearArbol()there is no initialization of thetListamember, so it points at garbage. You need to allocate the space for it to point to, and set thetListamember to point to it; then you can set thefondomember of that allocated space. Make sure you initialize every member of every structure…Update 1: fixed notation in
crearArbol()– the extra parentheses are needed. You also have to worry about the call tocrearArbol()inmain(), which I missed before. You are missing areturnfromAgregarCuenta(), or the return type should bevoidand the otherreturnstatements in the function would lose the value. Since you don’t check the returned value, it is not clear which is better.Update 2: this code compiles and runs. It leaks memory, of course.
When run with
valgrind, I get: