0
votes

I'm testing trie with valgrind, and having "Conditional jump or move depends on uninitialised value(s)" error after first symbol pass to function create_trienode.

I have struct:

typedef struct TrieNode{
    struct TrieNode **children;
    bool is_word;
} TrieNode;

func create_trienode:

struct TrieNode *create_trienode(char c, struct TrieNode *parent){
    struct TrieNode *node = malloc(sizeof(struct TrieNode)); 
    node->children = malloc(ALPHABET_SIZE*sizeof(struct TrieNode*)); 
    node->is_word=false;
    return node; 
}

and func create_tree

struct TrieNode *create_tree(FILE *file) 
{
struct TrieNode *root = create_trienode(' ', NULL);
struct TrieNode *ptr = root;
int character;
int converted;
int buffer;

//This handles if file does not end with a newline
character = fgetc(file);
buffer = fgetc(file);

while(character != EOF) 
{
  character = tolower(character);

  if (character == 10) // case newline
  {

  }
  else 
  if(isalpha(character))  
  {

      converted = character - 'a';
      if(ptr->children[converted] == NULL) // CONDITIONAL JUMP HERE
      {
          ptr->children[converted] = create_trienode(character, ptr);
      }

      ptr = ptr->children[converted];  

  }

  if (character == 92) 
  {
      if(ptr->children[ALPHABET_SIZE] == NULL) 
      {
          ptr->children[ALPHABET_SIZE] = create_trienode(character, ptr);
      }
      ptr = ptr->children[ALPHABET_SIZE];
  }

  if(ptr != root && (!(character == 92|| isalpha(character)) || buffer == EOF)) 


  {
      ptr->is_word = true;
      ptr = root;
      word_count++;
  }

  character = buffer;
  buffer = fgetc(file);
}

on the line if(ptr->children[converted] == NULL) valgrind says "Conditional jump or move depends on uninitialised value(s)" How do I solve this problem?

1
For a start, the initialisation should be node->children = malloc(ALPHABET_SIZE*sizeof(struct TrieNode *)); (note the extra *...)Oliver Charlesworth
Also, I don't believe this is your real code. You've defined create_trienode to take one argument, but you're passing two when you call it.Oliver Charlesworth
It's a mistake create_trienode should pass two argument. Thx for * note, minus half of lost bytesTom
always check (!=NULL) the returned value from malloc, before using that valueuser3629249

1 Answers

2
votes

You compares ptr->children[converted] with NULL, but don't initialized it to any value.

After malloc, the space isn't NULLed, so ptr->children[converted] mustn't be 'NULL', it could be any value.

To fix it, you could init ptr->children[converted] to NULL after your malloc.