可能有很多错误,但这是一个很大的错误
user *item = (user*) malloc(sizeof(struct user));
应该
user *item = new user;
在C ++中你应该 的 总是 强> 使用 new 。和...之间的不同 new 和 malloc 就是它 malloc 不会调用任何构造函数。所以在你的 user 对象的构造函数 string name 没有被召唤。因此,每当您尝试使用时,您都会有未定义的行为(即潜在的崩溃) name 。并且如评论中所述,您也应该使用 delete 不 free 基本相同的原因。
new
malloc
user
string name
name
delete
free
看了一下代码后面有很多很多指针相关的bug。比如这个怎么样
list* temp = (list*)malloc(sizeof(struct friend_list)); temp = hashArray[ascii_key]->FriendList;
暂时忘掉malloc vs new,看看上面的代码吧。你有一个指针 temp 你指出一些分配的内存。然后你扔掉那个记忆并制造 temp 指向 hashArray[ascii_key]->FriendList 代替。如果不使用它,分配内存有什么意义?然后通过释放函数末尾的内存来复合错误。
temp
hashArray[ascii_key]->FriendList
free(temp);
但 temp 不再指向已分配的内存(因为您将其指向了好友列表)。很明显,你还没有理解指针和内存分配。
这是你应该如何写这个功能
void check_friendship( int ascii_key, string name) { list* temp = hashArray[ascii_key]->FriendList; while( temp != NULL) { if(strcmp(temp->name.c_str(), name.c_str()) == 0) { cout<<"Friendship exist"<<endl; return; } temp = temp->next; } cout<<"No Record of Friendship"<<endl; }
看到 的 根本没有分配 强> 。我猜你脑子里有某种规则,不管有指针我必须分配一些记忆。这不是真的,分配是关于创建新对象。 check_friendship 不创建任何新对象(它只检查现有对象),因此它不需要分配或释放任何东西。
check_friendship
remove_friendship 有同样的问题,因为它正在消除友谊 delete 一个对象,(友谊被删除),但没有理由分配任何东西。
remove_friendship
add_friendship 有相同的错误,但相反。 add_friendship 应该为添加的友谊分配一个新对象,你这样做,但是然后你尝试在函数结束时释放对象。你在某种一揽子规则下运行,必须分配每个指针变量,然后释放,而不是逻辑地思考每个函数需要创建或销毁的对象。
add_friendship