【问题标题】:How to properly allocate memory for this linked list如何为这个链表正确分配内存
【发布时间】:2019-03-14 06:45:05
【问题描述】:

我似乎找不到内存分配的问题所在。所有功能都正常工作,但程序在执行过程中随机崩溃。我知道错误在于我如何为链表分配内存,但我似乎无法弄清楚哪一部分是错误的。

#include <iostream>
#include <string.h>
#include <stdio.h>
#include <cstring>

using namespace std;
void menu_function(void);
void command_execute(string command, string name1, string name2);
int hash_function(string str);
void insert_into_hashtable(int ascii_total, string name);
void add_friendship(int ascii_key, string name);
void print_friendships(int aascii_key);
void check_friendship(int ascii_key, string name);
void remove_friendship(int ascii_key, string name);

#define SIZE 125

struct friend_list {
    string name = "";
    struct friend_list * next;
};

typedef struct friend_list list;

struct user {
    string name;
    int key;
    friend_list * FriendList;
};

struct user * hashArray[SIZE];

int main(int argc,
    const char * argv[]) {

    menu_function();
    return 0;
}

void menu_function() {
    char user_input[100]; //this could limit the size of input
    string command;
    string name1 = "\0";
    string name2 = "\0";;
    char * token; ** strong text **
        int inputsize = 100;
    int i = 0;
    char delimit[] = " \t\r\n\v\f";
    while (1) {
        printf("\nP <Name> to create a person\n");
        printf("F <Name> <Name> record friendship\n");
        printf("U <Name> <Name> terminate friendship\n");
        printf("L <Name> print out friends of a specified person\n");
        printf("Q <Name> <Name>  check friendship status of two people\n");
        printf("X - terminate the progarm\n");

        // Determine user input and
        fgets(user_input, inputsize, stdin);
        //getline(&input, &inputsize, stdin);//takes in user input;

        //printf("input: %s", user_input);

        //parsing the string for the data within
        token = strtok(user_input, delimit);
        i = 0;
        while (token != NULL) {
            if (i == 0) {
                command = token;
                //cout<< command<<endl;
            }
            if (i == 1) {
                name1 = token;
                // cout<< name1<<":"<<endl;
            }
            if (i == 2) {
                name2 = token;
                //  cout<< name2<<":"<<endl;
                name1 = name1 + "\n";
            }
            token = strtok(NULL, " ");
            i++;
        }
        command_execute(command, name1, name2);
        command = '\0';
        name1 = '\0';
        name2 = '\0';
    }
}

void command_execute(string command, string name1, string name2) {
    //cout<<"command is: "<<command<<endl;

    switch (command[0]) {

    case 'P': //Create record of the person
        insert_into_hashtable(hash_function(name1), name1);
        break;
    case 'F': //Record friendship
        add_friendship(hash_function(name1), name2);
        add_friendship(hash_function(name2), name1);
        break;
    case 'U': //Terminate Friendship
        remove_friendship(hash_function(name1), name2);
        remove_friendship(hash_function(name2), name1);
        break;
    case 'L': //Print out the persons Friends
        print_friendships(hash_function(name1));
        break;
    case 'Q': //Check on friendship
        check_friendship(hash_function(name1), name2);
        break;
    case 'X': //Exit the program **** COMPLETED
        exit(1);
        break;

    default:
        cout << "Error occured based on your command please try again" << endl;
        break;
    }
}

int hash_function(string string) {
    //going to use the ASCI value of the name with different weights per array position to hash the names
    int ascii_key = 0;
    int ascii_total = 0;
    // cout<< string.length()<< endl;
    //cout<< string<< endl;
    for (int i = 0; i < string.length() - 1; i++) {
        ascii_total = (int) string[i] * (i * 3 + 1);
        //   cout<< string[i]<< endl;
    }
    ascii_key = ascii_total % SIZE;
    //deals with colisions through open hashing
    while (hashArray[ascii_key] != NULL && strcmp(hashArray[ascii_key] - > name.c_str(), string.c_str())) { //strcmp(hashArray[ascii_key]->name.c_str(), string.c_str())
        //hashArray[ascii_key] != NULL ||
        ascii_key++;
    }

    // ****** decide size of the hash table and then finished hashing function. Usually hash time is gonna be half full
    cout << ascii_key << endl;

    return ascii_key;
}

void insert_into_hashtable(int ascii_key, string name) {
    int k = 0;
    //get the hash key
    user * item = (user * ) malloc(sizeof(struct user));
    item - > name = name;
    item - > key = ascii_key;
    item - > FriendList = NULL;
    cout << ascii_key << endl;
    //collisions resolved by linear probing
    //store the user in the table

    hashArray[ascii_key] = item;
    k++;
    //free(item);
}

void add_friendship(int ascii_key, string name) {
    //gonna have to check for valid input on users
    list * add = (list * ) malloc(sizeof(struct friend_list));
    add - > name = name;
    add - > next = NULL;
    if (ascii_key == 13) {
        ascii_key = ascii_key;
    }
    /* if( hashArray[ascii_key]->FriendList->next == NULL )
     {
     cout<<hashArray[ascii_key]->FriendList<<endl;
     hashArray[ascii_key]->FriendList = temp;
     }
     else*/
    {
        add - > next = hashArray[ascii_key] - > FriendList;
        hashArray[ascii_key] - > FriendList = add;

    }
    free(add);
}

void print_friendships(int ascii_key) {
    friend_list * temp = (friend_list * ) malloc(sizeof(friend_list));
    temp = hashArray[ascii_key] - > FriendList;
    while (temp != NULL) {

        cout << temp - > name << endl;
        if (temp - > next == NULL) {
            free(temp);
            return;
        }
        temp = temp - > next;

    }
    //free(temp);
}

void check_friendship(int ascii_key, string name) {
    list * temp = (list * ) malloc(sizeof(struct friend_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;
    free(temp);
}

//need to finish
void remove_friendship(int ascii_key, string name) {
    list * temp = (list * ) malloc(sizeof(struct friend_list));
    list * prev = (list * ) malloc(sizeof(struct friend_list));
    temp = hashArray[ascii_key] - > FriendList;

    if (temp != NULL && temp - > name == name) {
        hashArray[ascii_key] - > FriendList = temp - > next; // Changed head
        // free old head
        return;
    }

    //not the head
    while (temp != NULL && temp - > name != name) {
        prev = temp;
        temp = temp - > next;
    }
    if (temp == NULL) return;

    // Unlink the node from linked list
    prev - > next = temp - > next;
    free(temp);
    free(prev);
}

【问题讨论】:

    标签: c++ memory linked-list allocation


    【解决方案1】:

    可能有很多错误,但这是一个很大的错误

        user *item = (user*) malloc(sizeof(struct user));
    

    应该是

        user *item = new user;
    

    在 C++ 中,您应该始终使用newnewmalloc 的区别在于malloc 不调用任何构造函数。因此,在您的 user 对象中,不会调用 string name 的构造函数。因此,每当您尝试使用 name 时,都会出现未定义的行为(即潜在的崩溃)。正如 cmets 中所述,出于基本相同的原因,您还应该使用 delete 而不是 free

    仔细查看代码后,发现了大量与指针相关的错误。比如这个怎么样

    list* temp  = (list*)malloc(sizeof(struct friend_list));
    temp = hashArray[ascii_key]->FriendList;
    

    暂时忘掉 malloc 与 new,看看上面的代码。你有一个指针temp 指向一些分配的内存。然后你扔掉那段记忆,让temp 指向hashArray[ascii_key]-&gt;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 不创建任何新对象(它只检查现有对象),因此它不需要分配或释放任何东西。

    remove_friendship 有同样的问题,因为它正在删除友谊,它应该 delete 一个对象,(友谊被删除)但没有理由分配任何东西。

    add_friendship 有相同的错误但相反。 add_friendship 应该为正在添加的友谊分配一个新对象,您这样做,但随后您尝试在函数结束时释放该对象。您在某种总括规则下操作,即必须分配每个指针变量然后释放,而不是从逻辑上考虑每个函数需要创建或销毁哪些对象。

    【讨论】:

    • 别忘了把free也替换成delete
    • 这解决了我的内存问题,但现在我的 add_function 不能正常工作。你觉得这个逻辑有什么问题吗?
    • 不是立即(除了已经指出的错误)。你知道如何使用调试器吗?解决此类错误的最佳工具。
    猜你喜欢
    • 2022-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-11
    • 2010-09-27
    相关资源
    最近更新 更多