I
Igal
hay, i'm doing this program. having problem wiht realloc in the
function that reads data structures into array (pointer - bp2), this
happens after reading the second record. when call to realloc.
i can't figure out what's wrong, think it's soming got to do with
freeing bp2.
and something called "corruption of the heap".
book* LoadBookData(unsigned *size)
{
FILE* fp;
int n = 0;
book *bp2 = NULL;
//open book data file
fp=fopen("book.bin","rb");
if (fp == NULL)
{
bp2 = (book*)calloc(0, sizeof(book));
return bp2;
}
<<<<<<<<<<<<<<<HERE>>>>>>>>>>>>>>
bp2 = realloc(bp2, sizeof(book));
if (bp2 == NULL) { perror("ERROR [realloc - LoadBookData()]");
exit(ERR_REALOC); }
//read data from file
while(fread(bp2,sizeof(book),1,fp) == 1)
{
if(ferror(fp)) { perror("ERROR [book.bin - read - LoadBookData()]");
exit(ERR_FREAD); }
bp2 = bp2 - n;
n++;
bp2 = realloc(bp2, sizeof(book));
if (bp2 == NULL) { perror("ERROR [realloc - LoadBookData()]");
exit(ERR_REALOC); }
bp2 = bp2 + n;
}
//close book data file
if (fclose(fp)==EOF)
{ perror("ERROR [book.bin - close - LoadBookData()]]");
exit(ERR_FCLOSE); }
*size = n;
return bp2;
}
function that reads data structures into array (pointer - bp2), this
happens after reading the second record. when call to realloc.
i can't figure out what's wrong, think it's soming got to do with
freeing bp2.
and something called "corruption of the heap".
book* LoadBookData(unsigned *size)
{
FILE* fp;
int n = 0;
book *bp2 = NULL;
//open book data file
fp=fopen("book.bin","rb");
if (fp == NULL)
{
bp2 = (book*)calloc(0, sizeof(book));
return bp2;
}
<<<<<<<<<<<<<<<HERE>>>>>>>>>>>>>>
bp2 = realloc(bp2, sizeof(book));
if (bp2 == NULL) { perror("ERROR [realloc - LoadBookData()]");
exit(ERR_REALOC); }
//read data from file
while(fread(bp2,sizeof(book),1,fp) == 1)
{
if(ferror(fp)) { perror("ERROR [book.bin - read - LoadBookData()]");
exit(ERR_FREAD); }
bp2 = bp2 - n;
n++;
bp2 = realloc(bp2, sizeof(book));
if (bp2 == NULL) { perror("ERROR [realloc - LoadBookData()]");
exit(ERR_REALOC); }
bp2 = bp2 + n;
}
//close book data file
if (fclose(fp)==EOF)
{ perror("ERROR [book.bin - close - LoadBookData()]]");
exit(ERR_FCLOSE); }
*size = n;
return bp2;
}