Home > database >  c deleting element in dynamic struct
c deleting element in dynamic struct

Time:12-28

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

CodePudding user response:

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.
  • Related