我正在尝试进行这3种操作,添加,删除和搜索。但是,当我尝试删除某些值不起作用时,我想知道我在此函数中做错了什么,和/或是否正确编写了其他函数。这是整个代码。 如果我尝试两次删除相同的值:free():在tcache 2中检测到double free
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define size_table 10
typedef struct Citizen citizen;
typedef struct Citizen{
char name[20];
int age;
citizen *next;
citizen *table[size_table];
} citizen;
int hash_function(int age){
return 10 - 2 - age % (size_table-2);
}
citizen *hash_add(citizen *tab, int age, char *name){
int position = hash_function(age);
citizen *new_citizen = (citizen*)malloc(sizeof(citizen));
new_citizen->next = tab->table[position];
new_citizen->age = age;
strcpy(new_citizen->name,name);
tab->table[position] = new_citizen;
return new_citizen;
}
citizen *hash_search(citizen *tab, int age){
int position = hash_function(age);
citizen *new_search = tab->table[position];
while(new_search != NULL){
if(new_search->age == age) return new_search;
new_search = new_search->next;
}
return NULL;
}
void hash_delete(citizen *tab, int age){
int position = hash_function(age);
citizen *new_delete = hash_search(tab,age);
new_delete = tab->table[position];
free(new_delete);
}
void clean_screen(){ system("clear"); }
void menu(){
"\033[0;32mi -Insert \n"
"\033[0;33mr -Remove \n"
"\033[0;34ms -Search \n"
);
}
int main(){
clean_screen();
menu();
citizen ct;
int age;
char get_name;
char choice;
while(scanf("%c",&choice) != EOF){
switch(choice){
case 'i':
clean_screen();
printf("Insira a idade: ");
scanf("%d",&age);
printf("Insira o nome: ");
scanf("%c ",&get_name);
hash_add(&ct,age,&get_name);
printf("Elemento adicionado ");
clean_screen();
menu();
break;
case 'r':
clean_screen();
printf("Remover a idade: ");
scanf("%d",&age);
hash_delete(&ct, age);
clean_screen();
menu();
break;
case 's':
clean_screen();
printf("Digite a idade: ");
scanf("%d",&age);
citizen *get_search = hash_search(&ct,age);
clean_screen();
if(get_search != NULL) printf("Idade %d encontrada\n", age);
else printf("idade %d não exise\n",age);
menu();
break;
}
}
return 0;
}