C - realloc with array of structs -
i'm doing array of structs dynamic allocate list of products works few times (3~5 times) , got error.
* error in `./test': realloc(): invalid next size: 0x000055bc0b44f260 *
here code, part of work college.
#include <stdio.h> #include <stdlib.h> typedef struct { int cod; float price; } product; int main () { file *fp; fp = fopen("products.txt", "r+"); if(fp == null) fopen("products.txt", "w+"); int control = 1; int choice; int tam = 0; int i; product *p1; p1 = malloc(sizeof(product)); while(fread(&p1[0], sizeof(product), 1, fp) != null){ tam++; } if(tam > 1){ rewind(fp); p1 = malloc((tam) * sizeof(*p1)); (int = 0; < tam; i++){ fread(&p1[i], sizeof(product), 1, fp); } } rewind(fp); { printf("1 - add product\n2 - show products\n3 - exit\n-> "); scanf(" %d", &choice); switch (choice) { case 1: if (tam == 0) { //p1 = malloc(sizeof(product)); printf("digit product code: "); scanf(" %d", &p1[tam].cod); printf("digit product price: "); scanf(" %f", &p1[tam].price); tam++; } else { printf("***realloqing: %d***\n", tam * sizeof(*p1)); p1 = (product*)realloc(p1, (tam) * sizeof(product)); (i = tam; > 0; i--) { p1[i].cod = p1[i-1].cod; p1[i].price = p1[i-1].price; } printf("digit product code: "); scanf(" %d", &p1[0].cod); printf("digit product price: "); scanf(" %f", &p1[0].price); tam++; } break; case 2: (i = 0; < tam; i++) { printf("product code: %d\nproduct price: %f\n", p1[i].cod, p1[i].price); } break; case 3: control = 0; break; } } while (control); (int = 0; < tam; i++){ fwrite(&p1[i], sizeof(product), 1, fp); } fclose(fp); free(p1); return 0; }
the problem here:
printf("***realloqing: %d***\n", tam * sizeof(*p1)); p1 = (product*)realloc(p1, tam * sizeof(product));
when tam
is, 1, realloc tam * sizeof(product)
, need realloc (tam + 1) * sizeof(product)
, because need space 2 products.
so fixes problem:
printf("***realloqing: %d***\n", (tam + 1) * sizeof(*p1)); p1 = (product*)realloc(p1, (tam + 1) * sizeof(product));
Comments
Post a Comment