简体   繁体   中英

c deleting element in dynamic struct

i'm trying to delete a single element in the struct and override this position with the last one. Here is my code of a function:

int deleteElement(struct record **rec, int *length, int elementToDelete){
    struct record *temp = NULL;

    allocateTempMemory(&temp, ((*length) - 1));

    for (int i = 0; i < ((*length) - 1); i++){
        if (elementToDelete != i){
            temp[i] = (*rec)[i];
            temp[i].ID = (*rec)[i].ID;
            temp[i].Salary = (*rec)[i].Salary;
            strcpy(temp[i].Name, (*rec)[i].Name);
        } else {temp[i] = (*rec)[(*length) - 1]; 
                temp[i].ID = (*rec)[(*length) - 1].ID;
                temp[i].Salary = (*rec)[(*length) - 1].Salary;
                strcpy(temp[i].Name, (*rec)[(*length) - 1].Name);
                };
    }
    
    free(*rec);
    *rec = temp;
    
     for (int i = 0; i < ((*length) - 1); i++){
        (*rec)[i] = temp[i];
        (*rec)[i].ID = temp[i].ID;
        (*rec)[i].Salary = temp[i].Salary;
        strcpy((*rec)[i].Name, temp[i].Name);
    }

    (*length)--;


    free(temp);

    return 1;
}

code of the struct

struct record{
    char Name[100];
    double Salary;
    int ID;
};

code of the function allocateTempMemory:

int allocateTempMemory(struct record **temp, int length){
    *temp = (struct record **)malloc(sizeof(struct record) * length);

    if (temp == NULL){
        return 0;
    }

    return 1;
}

However, it does not work properly. My guess are memory allocation issues (sometimes it runs through and sometimes it crashes immediately). Do you have any idea what the problem may be? thanks

You assign temp to *rect, than you free temp. basically you freed *rec. When you access *rec later it will cause crash.

*rec = temp;
....
free(temp); // cause *rec freed. Should not be freed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM