以下文件编写代码有什么问题?

时间:2012-02-25 09:02:12

标签: c file linked-list access-violation

我有以下用于为指纹创建哈希表的结构

typedef struct fpinfo
{ 
   unsigned long chunk_offset;
   unsigned long chunk_length;
   unsigned char fing_print[33];
}fpinfo;

/ *  *以下定义哈希表中的一个条目。  * /

typedef struct Hash_Entry 
{
   struct Hash_Entry *next; /* Link entries within same bucket. */
   unsigned namehash;   /* hash value of key */
   struct fpinfo fp;
} Hash_Entry;

typedef struct Hash_Table 
{
   struct Hash_Entry **bucketPtr;   /* Buckets in the table */
   int numBuckets;
   int        buck_entry_count[64];//number of entries in each bucket
   int      size;       /* Actual size of array. */
   int      numEntries; /* Number of entries in the table. */
   int      mask;       /* Used to select bits for hashing. */
} Hash_Table;

我使用

将指纹插入其中
int Hash_CreateEntry(Hash_Table *t, struct Hash_Entry he)
{
Hash_Entry *e;
const char *p;
int keylen;
struct Hash_Entry **hp;
unsigned long h = 0, g,i=0;

while ( i<5 ) 
 {
    h = ( h ) + he.fp.fing_print[i]++;
     g = h & 0xF0000000;
    h ^= g >> 24;
    h &= ~g;
    i++;
}

p =(const char*) he.fp.fing_print;
for (e = t->bucketPtr[h & t->mask]; e != NULL; e = e->next)
{
    if (e->namehash == h && strcmp((const char *)(e->fp).fing_print, p) == 0)
    {
        printf("\n%d \t%s",(e->fp).chunk_length,(e->fp).fing_print);
        return (1);
    }
}

if (t->numEntries >= rebuildLimit * t->size)
    WriteHTtoFile(t);
e = (Hash_Entry *)malloc(sizeof(*e) /*+ keylen*/);
hp = &t->bucketPtr[h & t->mask];
e->next = *hp;
*hp = e;
e->namehash = h;
strcpy((char *)(e->fp).fing_print, p);
t->numEntries++;
t->buck_entry_count[h & t->mask]++;
return (0);
}

我用来写HT文件的代码是

static void   WriteHTtoFile(Hash_Table *t)
{
Hash_Entry *e, *next = NULL, **hp, **xp;
int i=0, mask;
    Hash_Entry **oldhp;
int oldsize;
FILE *htfile=fopen("htfile.txt","a");
system("cls");

for ( hp = t->bucketPtr;t->bucketPtr!=NULL;hp=t->bucketPtr++)
    {
    for (e = *hp;e ->next!= NULL;e = e->next) 
    fprintf(htfile,"\n%d \t%s",(e->fp).chunk_length,(e->fp).fing_print);        
    }
fclose(htfile);
}

我的问题是(是)

1 - 它表示“访问冲突读取位置0xfdfdfe09”。写了相当多次后(它写了6401指纹)。它表示故障行是文件写入功能中的fprintf()。

2-它写的指纹和写之前的指纹根本不匹配。实际上编译器中指纹的十六进制表示(我正在使用VC2010)和程序读取的指纹是不同的。

3-所有条目的chunck_length值均为3452816845l

2 个答案:

答案 0 :(得分:1)

我想WriteHTtoFile中的循环看起来应该更像这样:

for (i = 0; i < t->numBuckets; ++i)
{
    for (e = t->bucketPtr[i]; e && e->next; e = e->next) 
        fprintf(htfile, /*...*/);        
}

答案 1 :(得分:0)

你有更多的问题;这段代码无可救药地拙劣了

  • WriteHTToFile会修改原始哈希表,因此最终会导致内存泄漏
  • 您使用%d格式打印fing_print;它根本不清楚fing_print是/应该是什么(二进制字符串; ascii字符串)。

获得一本关于C的好书,并使用调试器进行练习。

相关问题