Search code examples
cstructmalloccorruption

double free or corruption (!prev) error with program in C


When running my program I get such error :

*** glibc detected *** ./prog: double free or corruption (!prev): 0x09155170 ***

The problem is obviously with giving the memory to the struct via malloc, but I can't get what's wrong with it. Here is the code of my program (in C) :

#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
#include <string.h>

typedef struct 
{
      char kood[4];
      int kogus;
      char nimetus[80];
      double hind;
      int P;
      int K;
      int A;
}ese;

void sort(int m, ese* d);

void search_kood(int m, ese* d);

void search_nimetus(int m, ese* d);

void search_kuupaev(int m, ese* d);

int menu();

int main (void)
{
    FILE *list;
    list = fopen("elektroonikapood.txt", "r");
    int menu_valik,m,i;
    m=0;
    if (list==NULL)
      {
            printf("Empty or corrupted file!");
            getchar();
            return 0;   
      }  
    ese *esemed = (ese*) malloc(sizeof(ese)); 
    while(!feof(list)) 
      {

                  fscanf(list, "%s", esemed[m].kood);
                  fscanf(list, "%d", &esemed[m].kogus);
                  fscanf(list, "%s", esemed[m].nimetus);
                  fscanf(list, "%lg", &esemed[m].hind);
                  fscanf(list, "%d", &esemed[m].P);
                  fscanf(list, "%d", &esemed[m].K);
                  fscanf(list, "%d", &esemed[m].A);
                  m++;
      }


    while(1)
   { menu_valik = menu();
    if(menu_valik == 1)
      sort(m, esemed);
    else if (menu_valik == 2)
      search_kood(m, esemed);
    else if (menu_valik == 3)
      search_kuupaev(m, esemed);
    else if (menu_valik == 4)
      search_nimetus(m, esemed);
    else if (menu_valik == 0)
        {
          free(esemed);
          fclose(list);
          exit(1);
       }
    else
      break;
     }
     return 0;
}

There are also some additional functions , but I don't think there is a problem with them.


Solution

  • First... don't cast malloc in C. It can hide errors.

    Second... your malloc is outside the while( !feof( list ) ) loop yet it only allocates a single instance of the ese structure, but you're loop implies you're loading multiple instances... which means you're overwriting memory... at which point all bets are off.

       ese *esemed = NULL; 
       ese *lastItem = NULL;
    
       while(!feof(list)) 
       {
            ese* newItem = malloc( sizeof( ese ) );
    
            if( !esemed ) esemed = newItem;
            if( lastItem ) lastItem->next = newItem;
    
            lastItem = newItem;
    
            fscanf(list, "%s", newItem->kood);
            fscanf(list, "%d", &newItem->kogus);
            fscanf(list, "%s", newItem->nimetus);
            fscanf(list, "%lg", &newItem->hind);
            fscanf(list, "%d", &newItem->P);
            fscanf(list, "%d", &newItem->K);
            fscanf(list, "%d", &newItem->A);
        }