Igal wrote:
> 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;
> }
* Don't cast calloc/malloc/realloc etc.
* Why assign to bp2 at all?
* There is no way that your code can signal an error here, i.e. the
calling
code can't distinguish between a non-existant and empty file.
> bp2 = realloc(bp2, sizeof(book));
> if (bp2 == NULL) { perror("ERROR [realloc - LoadBookData()]");
> exit(ERR_REALOC); }
Here, you exit on realloc() failure, above, you return NULL when calloc()
fails. I'd suggest using some kind of xalloc().
> //read data from file
> while(fread(bp2,sizeof(book),1,fp) == 1)
Note: the binary layout of structures depends on the compiler and system.
It
is for sure not easily ****table to store binary dumps of structures in a
file like that.
> {
> if(ferror(fp)) { perror("ERROR [book.bin - read - LoadBookData()]");
> exit(ERR_FREAD); }
> bp2 = bp2 - n;
> n++;
>
> bp2 = realloc(bp2, sizeof(book));
Problem here: the pointer you pass to realloc() _MUST_ have been acquired
by
a former call to realloc()/malloc(). Suggestion:
book tmp;
while(read_book( &tmp, fp)) {
bp2 = xrealloc( bp2, (n+1)*(sizeof *bp2));
bp2[n++] = tmp;
}
cheers
Uli


|