On May 3, 7:21 pm, Igal <igal.al...@[EMAIL PROTECTED]
> 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. I'm not sure what the results of calloc(0, N) are,
but if they are similar of malloc(), then that pointer is not really
reliable.
You most likely want something like this:
return calloc(0, sizeof book);
> }
> <<<<<<<<<<<<<<<HERE>>>>>>>>>>>>>>
Comment your code with /* */
> bp2 = realloc(bp2, sizeof(book));
That's actually a malloc(), since bp2 was initialized to NULL before,
and realloc(NULL, N) is equal to malloc(N)
> if (bp2 == NULL) { perror("ERROR [realloc - LoadBookData()]");
> exit(ERR_REALOC); }
Are you sure you want to exit here? And what is the value of
ERR_REALOC?
>
> //read data from file
> while(fread(bp2,sizeof(book),1,fp) == 1)
> {
> if(ferror(fp)) { perror("ERROR [book.bin - read -
LoadBookData()]");
fread() can't return the count (third parameter) if an error in the
stream occurs.
> exit(ERR_FREAD); }
Memory leak here, you don't free `bp2'.
> bp2 = bp2 - n;
> n++;
Why?
>
> bp2 = realloc(bp2, sizeof(book));
If `bp2' doesn't point to a pointer returned by realloc, malloc or
calloc, realloc() will produce undefined results (unless `bp2's value
is NULL)
But I *see* what you are trying to do, here's the actual logic:
size_t n = 0;
back:
if(fread(&bp2[n], sizeof bp2[0], 1, fp) != 1) { /* handle error or EOF
*/ }
n++;
bp2 = realloc(bp2, n+1 * sizeof bp2[0]);
if(bp2 == NULL) { /* ... */ }
goto back;


|