I’m encountering an issue while reading an file that contains records with length indicators and fields separated by ‘|’. In this program, I’m reading information about the quantity and price of a product and summing them up. However, when I attempt to use realloc()
for my buffer variable, I encounter unexpected behavior. Strangely, the result I’m expecting is 118.239998, but when I use realloc()
, the result becomes 118.275002. Surprisingly, when I use free(buffer)
and then allocate memory again using malloc()
for the buffer, I get the correct result.
This is the file
The first byte serves as a length indicator, and both ‘n'(10 in decimal) and ‘NL'(13 in decimal) also serve as indicators.
OUTPUT WITH FREE + MALLOC
OUTPUT WITH REALLOC
here is my code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
char *buffer, *produto;
int tamRegistro, quantidade;
float preco, total = 0;
FILE* arquivo;
arquivo = fopen("compras.txt", "r");
if (arquivo == NULL) {
printf("Erro ao abrir o arquivon");
system("pause");
exit(1);
}
//take the first length indicator
tamRegistro =fgetc(arquivo);
buffer = (char*)malloc(sizeof(char) * tamRegistro);
if (buffer == NULL) {
printf("Falha ao alocar memorian");
exit(1);
}
while (fread(buffer, tamRegistro, 1, arquivo) == 1) {
//separate fields
printf("LENGTH:%d-", tamRegistro);
produto = strtok(buffer, "|");
printf("%s-", produto);
quantidade = atoi(strtok(NULL, "|"));
printf("%d-", quantidade);
preco = atof(strtok(NULL, "|"));
printf("%f-n", preco);
total += (preco * quantidade);
//take next length indicator
tamRegistro = fgetc(arquivo);
*buffer=(char*)realloc(buffer,sizeof(char)*(tamRegistro));
}
free(buffer)
fclose(arquivo);
printf("%fn",total);
return 0;
}
10
You use strtok
to break up the buffer, but that doesn’t contain a string as long as it isn’t terminated by a null character; so you have to allocate one more byte and store the NUL there.
8