【问题标题】:Assigning values error C赋值错误 C
【发布时间】:2015-07-09 15:57:50
【问题描述】:

我是 C 新手,但在指针和值方面遇到了一些问题。

所以我正在制作一个哈希表,我的插入函数出现错误(错误发布在代码之后):

typedef struct WordList {
   char *word;
   struct WordList *next;
} WordList;

typedef struct HashTable {
   int key;
   struct WordList *value;
   struct HashTable *next;
} HashTable;

#define TABLE_SIZE 8192

HashTable *table[TABLE_SIZE] = { NULL };

//Insert element
void insertElement(int key, char *word) {
   int i = 0;

   // check if key has already existed
   while((&(table[i]->key) != NULL) && (i < TABLE_SIZE)) {
      // !!!! ERROR HERE !!!! if(table[i]->key == key) { // if find key    
         // ... implementation

         return; // exit function and skip the rest
      }

      i++; // increment loop index 
   }

   // find a NULL slot and store key and value
   if(&(table[i]->key) == NULL) {
      // !!! ERROR HERE!!! table[i]->key = key;

      // ... implementation
   }
}

int main() {
   // test call
   insertElement(1, "blah\0");

   int i;

   for ( i=0; i < 10; i++)
   {
      printf("%d: ", i);

      struct HashTable *tableTemp = table[i];

      while (tableTemp != NULL)
      {
         printf("(%d)\n", tableTemp->key);
         tableTemp = tableTemp->next;
      }

      printf("\n");
   }

   return 0;
}

我使用 valgrind,这是分配表 [i]-> key = key 的错误

Invalid write of size 4
Address 0x0 is not stack'd, malloc'd or (recently) free'd

【问题讨论】:

  • 地址0x0为空指针;您正在尝试使用空指针写入一个 4 字节的值(可能是 int)。喜欢int *p = 0; *p = 1;
  • 你在哪里为table[i]分配内存?数组table 是一个指针 数组,你初始化为NULL,如果你不让它们指向任何有效的内存,你就会得到那个错误。
  • 为什么不只分配表[大小] 并使用点表示法?否则你必须 malloc 每个。

标签: c pointers hashtable


【解决方案1】:

一般来说,地址0x0是空指针;您正在尝试使用空指针写入一个 4 字节的值(可能是 int)——例如 int *p = 0; *p = 1;,但它可能并不那么明显。

在你的骨架代码中,你有:

if (&(table[i]->key) == NULL) {
    // !!! ERROR HERE!!! table[i]->key = key;

评论:

  1. 您应该已经显示了错误的实际代码。我们不得不猜测,因为你没有展示它。

  2. 您刚刚验证了table[i]-&gt;key 的地址是一个空指针,当您尝试将table[i]-&gt;key = key; 分配给它时会导致问题。

以后,请提供足够多的真实代码,以便我们可以看到您的 MCVE (How to create a Minimal, Complete, and Verifiable Example?) 或 SSCCE (Short, Self-Contained, Correct Example) — 两个名称和链接表示相同的基本思想。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-05-06
    • 2012-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多