Afficher un message
Vieux 08/05/2008, 16h52   #7
Jim Langston
Aucun Avatar
 
Messages: n/a
Hébergeur:
Par défaut Re: realloc problem, corrupt last item

Igal wrote:
>> You have not provided sufficient information for me to you
>> effectively. On general principles, lose the cast, replace
>> sizeof(book) with sizeof *bp, use a temp to catch the result of
>> realloc in case it fails and returns NULL, and make sure you have
>> #included <stdlib.h>. Note that bp is a copy of the calling
>> function's pointer; the original will not be updated automatically,
>> so if you want to keep the new value you must provide a mechanism
>> for the caller to assign this new value to the original pointer.

>
> here's the full function.
> i call it like this:
>
> bp = AddBook(bp, &BOOK_SIZE);
>
> /*#############################
> # Add Book Function #
> #############################*/
> book* AddBook(book *bp, unsigned *size)
> {
> book temp;
> unsigned n = *size; //n = size of book array
> bool check = FALSE;
> char str_cn[80];
> int i;
>
> printf("%d", (int)(sizeof(bp)/sizeof(bp[0])));


bp is a book*. Therefore, it's size is the size of a pointer (most likely 4
bytes). This is most likely not giving you what you want. You need to keep
track of the size for dynamically allocated arrays.

> n++;
> bp = (book*)realloc(bp, sizeof(book));


And here you are allocating space for *one* book. You need to allocate size
+ 1 (which is in n at this point) so this line should become:

bp = realloc( bp, sizeof(book) * n );

> if (bp == NULL) { perror("ERROR [realloc - AddBook()]");
> exit(ERR_REALOC); }
>
> printf("\n[Add Book to Catalog]\n");
>
> //get catalog number
> while(check != TRUE)
> {
> printf("Book Catalog Number: ");
> _flushall();
> gets(str_cn);
>
> //check if string is longer then 9 digits. if longer then error.
> if(strlen(str_cn) > 9) { check = FALSE; printf("[E] catalog number
> too long, 9 digit max.\n"); continue; }
>
> //check each letter in string if a digit, if all are then check =
> TRUE, else check = FALSE
> i=0;
> while(str_cn[i])
> {
> if(isdigit(str_cn[i])) { check = TRUE; i++; continue; }
> else { check = FALSE; printf("[E] catalog number not valid, try
> again.\n"); break; }
> }
>
> if(check == TRUE) { temp.cn = atol(str_cn); } //if all OK, put value
> in str_cn
> }
> check = FALSE;
>
> ... here i get data into temp, and check validation ...
>
> *size = n;
>
> bp[n-1].cn = temp.cn;
> bp[n-1].Units = temp.Units;
> bp[n-1].Year = temp.Year;
> bp[n-1].Price.CostPrice = temp.Price.CostPrice;
> bp[n-1].Price.RetailPrice = temp.Price.RetailPrice;
>
> strcpy(bp[n-1].Publisher, temp.Publisher);
> strcpy(bp[n-1].BookName, temp.BookName);
> strcpy(bp[n-1].Author.Author1, temp.Author.Author1);
> strcpy(bp[n-1].Author.Author2, temp.Author.Author2);
> strcpy(bp[n-1].Author.Author3, temp.Author.Author3);
>
> return bp;
> }


--
Jim Langston
tazmaster@rocketmail.com


  Réponse avec citation
 
Page generated in 0,07561 seconds with 9 queries