struct - double free or corruption (!prev) error with program in C -
when running program such error :
*** glibc detected *** ./prog: double free or corruption (!prev): 0x09155170 ***
the problem giving memory struct via malloc, can't what's wrong it. here code of 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 additional functions , don't think there problem them.
first... don't cast malloc in c. can hide errors.
second... malloc outside while( !feof( list ) )
loop yet allocates single instance of ese structure, you're loop implies you're loading multiple instances... means you're overwriting memory... @ point bets 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); }
Comments
Post a Comment