Valgrind 错误:条件跳转或移动取决于 char 数组上的未初始化值,即使数组已初始化也是如此



当我运行这段代码时,我收到错误:条件跳转或移动取决于未初始化的值和使用大小为 8 的未初始化值,两者都在第 50 行。我知道我没有将任何字符/值放入"lcword"中,但这应该不是问题,因为我没有将未初始化的值分配给任何东西,而是将一些字符放入数组中以替换这些单位化值。我在条件中也没有看到任何未初始化的值 - 只有 j 被初始化。我应该如何解决这个问题?

unsigned int hash(const char *word)
{
char* lcword = malloc(46 * sizeof(char));
for (int j = 0; j < 46; j++)
{
lcword[j] = tolower(word[j]); //This is line 50
}
unsigned int hash = 0;
for (int i=0, n=strlen(lcword); i<n; i++)
{
hash = (hash << 2) ^ lcword[i];
}
free(lcword);
return hash % N;
}
//Source of hash function: https://github.com/andycloke/Harvard-CS50-Solutions/blob/master/pset5/speller/dictionary.c

这是整个文件(在检查和加载函数中调用哈希函数(:

// Implements a dictionary's functionality
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <ctype.h>
#include "dictionary.h"
// Represents a node in a hash table
typedef struct node
{
char word[LENGTH + 1];
struct node *next;
}
node;
// Number of buckets in hash table
const unsigned int N = 65536;
// Hash table
node *table[N];
unsigned int sizeofdic = 0;
// Returns true if word is in dictionary else false
bool check(const char *word)
{
int i = hash(word);
node *cursor = table[i];
while (cursor != NULL)
{
if (strcasecmp(cursor->word, word) == 0)
{
return true;
}
else
{
cursor = cursor->next;
}
}
return false;
}
// Hashes word to a number
unsigned int hash(const char *word)
{
char* lcword = malloc(46 * sizeof(char));
for (int j = 0; j < 46; j++)
{
lcword[j] = tolower(word[j]);
}
unsigned int hash = 0;
for (int i=0, n=strlen(lcword); i<n; i++)
{
hash = (hash << 2) ^ lcword[i];
}
free(lcword);
return hash % N;
}

// Loads dictionary into memory, returning true if successful else     false
bool load(const char *dictionary)
{
FILE *dict = fopen(dictionary, "r");
node *newnode;
int index;
char *newword = malloc(46*sizeof(char));
while (fscanf(dict, "%s", newword) != EOF)
{
sizeofdic++;
newnode = malloc(sizeof(node));
strcpy(newnode->word, newword);
index = hash(newnode->word);
newnode->next = table[index];
table[index] = newnode;
}
fclose(dict);
free(newword);
return true;
}
// Returns number of words in dictionary if loaded else 0 if not yet     loaded
unsigned int size(void)
{
return sizeofdic;
}
// Unloads dictionary from memory, returning true if successful else     false
bool unload(void)
{
node *cursor;
node *tmp;
for (int i = 0; i < N; i++)
{
cursor = table[i];
while (cursor != NULL)
{
tmp = cursor;
cursor = cursor->next;
free(tmp);
}
}
free(cursor);
return true;
}

至少有一个问题是:j < 46.在很多(大多数?(情况下,读到"单词"的末尾

最新更新