1548132==ERROR: LeakSanitizer: detected memory leaks

1548132==ERROR: LeakSanitizer: detected memory leaks

我 运行 我的程序上的自动评分器出现了这个错误,但是当我 运行 手动执行完全相同的测试用例时,它似乎工作正常。我不确定为什么只有在使用自动分级机时才会出现错误。我是 C 的新手,我不明白为什么会发生内存泄漏,因为我已经释放了所有使用 malloc 的变量。它向我显示了具体是哪些行导致了错误,但我不知道如何在不“破坏”我的 code/output.

的情况下修复它

源代码:

struct Node* head; //global variable

void Insert(int x){
    struct Node* temp = (struct Node*)malloc(sizeof(struct Node));
    struct Node* ptr = head;
    
    //check if already present
    while(ptr != NULL){
        if(ptr->data == x){return;}
        ptr = ptr->next;
    }
    
    //check if head is greater
    if(head == NULL || head->data > x){
        temp->data = x;
        temp->next = head;
        head = temp;  
    }else{
        ptr = head;
        while(ptr->next != NULL && ptr->next->data < x){
            ptr = ptr->next;
        }
        
        temp->data = x;
        temp->next = ptr->next;
        ptr->next = temp;
    }
   
}
void Delete(int x){
    struct Node* temp = head;
    struct Node* prev;
    
    //if head has key
    if(temp != NULL && temp->data == x){
        head = temp->next;
        free(temp);
        return;
    }
    
    //find key
    while(temp != NULL && temp->data != x){
        prev=temp;
        temp = temp->next;
    }
    
    //if key isnt present
    if(temp == NULL){return;}
    
    //unlink
    prev->next = temp->next;
    
    free(temp);
}
void Print(){
    struct Node* temp = head;
    int c = 0;
    while(temp != NULL){
        c++;
        temp = temp->next;
    }
    printf("%d :", c);
    
    temp = head;
    while(temp != NULL){
        printf(" %d", temp->data);
        temp = temp->next;
    }
    printf("\n");
}

int main(){
    int x;
    char c;
    head = NULL; //empty list
    
    scanf(" %c%d",&c,&x);
    if(c == 'i'){
        Insert(x);
    }else if(c == 'd'){
        Delete(x);  
    }
    Print();
    while(scanf(" %c%d",&c,&x)!=EOF){
        if(c == 'i'){
            Insert(x);
        }else if(c == 'd'){
            Delete(x);
        } 
        Print();
    }
    
    return 0;
}

你的问题就在这里

void Insert(int x){
    struct Node* temp = (struct Node*)malloc(sizeof(struct Node));
    struct Node* ptr = head;
    
    //check if already present
    while(ptr != NULL){
        if(ptr->data == x){return;}  <--- If this return is executed, temp is not freed
        ptr = ptr->next;
    }

要修复它,只需移动 malloc 使其位于循环之后。

void Insert(int x){
    struct Node* ptr = head;
    
    //check if already present
    while(ptr != NULL){
        if(ptr->data == x){return;}
        ptr = ptr->next;
    }

    struct Node* temp = malloc(sizeof(struct Node));

顺便说一句:

  1. head 作为全局变量是个坏主意

  2. 不要转换 malloc

    返回的值