I have this code that reads a file that already exists, but in the first "for" when it read the file and copies it to the "struct" when the index is 1, I get an error:
(A buffer Read overrun has occurred in File.exe Which has corrupted the program's internal state. Press Break to debug the program or Continue to terminate the program.
For more details please see Help topic 'How to debug Buffer Overrun Issues'.)
#include "lerArquivo.h"
void main()
{
int nQtdRegistro;
int i;
REGISTRO stRegistro;
REGISTRO *ptrSalva;
REGISTRO *ptrVetRegistro;
LABEL stLabel;
FILE *fdArq;
fdArq = fopen(CAMINHO_NOME_ARQ, "rb");
if(fdArq == NULL)
{
cout << "Erro na abertura do arquivo: " << CAMINHO_NOME_ARQ<< endl;
}//if
if(fread(&stLabel, sizeof(stLabel), 1 , fdArq) == 0)
{
fclose(fdArq); // fechar o arquivo
cout << "Erro fread" << endl;
PAUSA;
exit(-1);;
}
ptrSalva = ptrVetRegistro = (REGISTRO *) malloc(stLabel.nQtdeRegistros * sizeof(REGISTRO));
if(ptrSalva == NULL)
{
cout<< "Não tem memoria para conter " << stLabel.nQtdeRegistros << " registros" << endl;
PAUSA;
exit(-1);
}
for(i = 0; i < stLabel.nQtdeRegistros; i++)
{
if(fread(&stRegistro + i, sizeof(stRegistro), 1 , fdArq) == 0)
{
fclose(fdArq); // fechar o arquivo
cout << "Erro fread" << endl;
PAUSA;
exit(-1);
}
memcpy(ptrVetRegistro + (i * sizeof(REGISTRO)) , &stRegistro, sizeof(REGISTRO));
}// for
for(i = 0; i < stLabel.nQtdeRegistros; i++)
{
cout << "Descrição: " << ptrVetRegistro[i].cDescricao << "\n";
cout << "Preço Unitario: " << ptrVetRegistro[i].dPrecoUnitario << "\n";
cout << "Quantidade: " << ptrVetRegistro[i].dQuatindade << "\n";
}
fclose(fdArq);
free(ptrSalva);
}
if(fread(&stRegistro + i, sizeof(stRegistro), 1 , fdArq) == 0). The variablestRegistrois not an array but a single value (so you should not be adding i). Maybe this should beptrSalva. – Loki Astari Nov 1 '12 at 15:24stackoverflow.com. There are more people over there and thus you are likely to get a quicker better response than over here. – Loki Astari Nov 1 '12 at 15:26ptrVetRegistro + (i * sizeof(REGISTRO))You need to look up pointer airthmatic. – Loki Astari Nov 1 '12 at 15:28