【发布时间】:2018-11-30 06:49:57
【问题描述】:
所以我正在创建一个密码库,并且需要能够将 HashTable 保存到二进制文件中,并在登录时将二进制文件中的相同内容读回程序 HashTable
我一直在玩 fwrite 和 fread 整整 4 个小时,但似乎找不到我哪里出错了。目前我正在segfaulting,我已经尝试GDB来找到它但只是得到消息:
Thread 2 received signal SIGSEGV, Segmentation fault.
0x00007fff9a9a16a0 in ?? ()
我的文件读取代码是:
void readFile(char * fileName, HTable * hashTable){
//Create file pointer and point it at fild to open
FILE * fp;
fp = fopen(fileName, "rb+");
//check if file exists
if(!fp){
printf("File could not be opened\n");
return;
}
//Set a temp Node to hold data, read data into the temp Node
//and insert temp into hashtable
Node * temp;
while(1){
fread(&temp, sizeof(Node), 1, fp);
insertData(hashTable, temp->key, temp->data);
if(feof(fp) != 0)
break;
printf("is this working?\n");
}
//Close file pointer
fclose(fp);
}
我写入文件的代码是:
void saveFile(char * fileName, HTable * hashTable){
//Create a FILE pointer and point it to the file to open or create
FILE * fp;
fp = fopen(fileName, "wb+");
//If the file does not exist or cannot be created give error message
if(!fp){
printf("ERROR: File could not be created\n");
return;
}
//for each index of the hashTable write its contents to the file
for(int i = 0; i < hashTable->size; i++){
Node * temp = hashTable->table[i];
while(temp != NULL){
fwrite(&temp, sizeof(Node), 1, fp);
temp = temp->next;
printf("saved....\n");
}
printf("Index %d saved\n", i);
}
//Close file pointer
fclose(fp);
}
我知道段错误不是来自 insertData 函数,因为我已经对其进行了测试并且知道它可以正常工作。对于我做错的事情,我最好的猜测是我的 fwrite 条件不正确,或者当我读取数据时,我在某处错误地管理了内存。
HashTable 结构也是:
typedef struct HTable
{
size_t size;
Node **table;
void (*destroyData)(void *data);
int (*hashFunction)(size_t tableSize, char * key);
void (*printData)(void *toBePrinted);
}HTable;
我击中的节点是:
typedef struct Node
{
char * key;
void *data;
struct Node *next;
} Node;
感谢您的任何反馈!
【问题讨论】:
-
您无法读取/写入键/数据的指针数据。您将需要读/写它们的值。
-
将原始指针写入磁盘,然后在不同的进程中读取和使用这些指针是导致崩溃和烧毁的秘诀。如果您没有做任何不方便的事情(例如在过渡期间释放内存),则写入磁盘的哈希表中的指针对于同一进程可能是可以的,但不建议这样做。您必须忽略写入磁盘的指针,或者安排不写入磁盘指针(可能是偏移量,可能是其他一些信息)。
-
temp是一个指针,您永远不会为它分配内存,但是您将数据读入它指向的任何位置。未定义的行为和简单的段错误。请查找有关如何使用调试器的教程,因为它可以帮助您解决遇到的每个问题,并告诉您哪里出了问题。 -
fread(&temp...不会在任何温度点读取数据。它在 temp 之上读取数据,然后继续粉碎堆栈。
标签: c io binary hashtable read-write