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 1 saves a license plate (matricula) and a name (proprietario) to a file
Case 2 reads the entire file and puts everything in memory. I'm having a problem here:
Code:
memptr = realloc(memptr, c*sizeof(registo));
As soon as it goes a second time through the cycle I get this error:
Code:
*** glibc detected *** ./ex1: realloc(): invalid next size: 0x0804a170 ***
It has something to do with this:
Code:
memcpy(memptr[c].proprietario, registo.proprietario, sizeof(registo.proprietario));
Because if I remove it I no longer get the error, for some reason why I try to put the name in memory it messes it up. I've already tried using strcpy instead, strlen instead of sizeof, even manually putting the amount of bytes to copy, always the same error.
Anyone have any idea what's wrong and what should I do instead?