1

I have a project that is required to store two variables for an AVL tree: a word and the rate that it is used:

struct AVLnodo {
  float peso;
  int FB;
  char *palavra;
  struct AVLnodo* esq;
  struct AVLnodo* dir;
};

Note:

peso=rate of use

palavra=word

other variables are pointers to child and factor's of balance.

The problem is in the code below:

wordTree* InsereAVL (wordTree *a, float peso, char *word, int *ok)
{
if (a == NULL)
  {
     a = (wordTree*) malloc(sizeof(wordTree));
     a->peso = peso;
     a->palavra = NULL;

     //1----->  strcpy(a->palavra,word);
     //2----->  a->palavra=word;

     a->esq = NULL;
     a->dir = NULL;
     a->FB = 0;
     *ok = 1;
 }
 else
 if (peso < a->peso)
 {
       ...
 }
 else
 {
       ...
 }
 return a;
}

The right way to copy the string is to use the strcpy, as shown by 1, but that is resulting in an execution error.

When using 2, the code works, but the word field on the struct of each node is stored with the same address, i.e all the nodes have a different numbers on peso (rate of use) but the same word on palavra(word), which is the last word added to the tree.

I'm not sure how to solve this problem. Hopefully someone will know how to fix it.

Thanks.

gavsta707
  • 365
  • 3
  • 16

2 Answers2

3

You need to allocate memory before copying word:

a->palavra = malloc(strlen(word)+1);

Bogolt
  • 520
  • 1
  • 3
  • 9
  • I did this and it worked! I used `a = (wordTree*) malloc(sizeof(wordTree));` thought it would allocate memory for the string field as well, thanks for the help! – Mateus Heck Jul 27 '17 at 20:39
  • `malloc(sizeof(wordTree));` allocates only enough memory for your struct. Pointers represent a different type than the type they are referring to. Note, that the pointer size may differ on varios architectures. – Laposhasú Acsa Jul 27 '17 at 20:51
1

I think you need to malloc the memory before you strcpy to a->palavra.

Laposhasú Acsa
  • 1,550
  • 17
  • 18