Code:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define NAME_BUFFER_SIZE 80
#define FICHEIRO "registo.bin"
typedef struct {
char matricula[6];
char proprietario[NAME_BUFFER_SIZE];
char apagado;
} veiculo_t;
int main()
{
int opcao = 0, c;
char matricula[10];
FILE *fp;
veiculo_t *memptr = NULL;
veiculo_t registo;
do
{
scanf("%d", &opcao);
getchar();
switch( opcao )
{
case 1:
fp=fopen(FICHEIRO,"ab+");
if (fp==NULL) printf("Impossivel aceder ou criar ficheiro");
else {
fgets(matricula,sizeof(matricula),stdin);
memcpy(registo.matricula, matricula, 6);
fwrite(registo.matricula, sizeof(registo.matricula),1,stdout);
fgets(registo.proprietario,sizeof(registo.proprietario),stdin);
registo.apagado='0';
fwrite(®isto, sizeof(registo),1,fp);
fclose(fp);
fflush(fp);
break;
}
case 2:
fp=fopen(FICHEIRO,"rb");
if (fp==NULL) printf("Impossivel aceder ou criar ficheiro\n\n");
else {
c=0;
while(fread(®isto,sizeof(registo),1,fp) != 0)
{
memptr = realloc(memptr, c*sizeof(registo));
memcpy(memptr[c].matricula, registo.matricula, 6);
memcpy(memptr[c].proprietario, registo.proprietario, sizeof(registo.proprietario));
c++;
}
fclose(fp);
fflush(fp);
}
break;
case 3:
printf("\n\nPrograma vai fechar!\n\n");
break;
default:
printf("\nOpcao invalida!!\n\n");
break;
}
}while (opcao != 3);
return(0);
}
Case 2 reads the entire file and puts everything in memory. I'm having a problem here:
Code:
memptr = realloc(memptr, c*sizeof(registo));
Code:
*** glibc detected *** ./ex1: realloc(): invalid next size: 0x0804a170 ***
Code:
memcpy(memptr[c].proprietario, registo.proprietario, sizeof(registo.proprietario));
Anyone have any idea what's wrong and what should I do instead?
