I am new to the world of C programming and at the moment I am exploring a combination of pointers, pointer arithmetic with file IO and memory management, all at once. Please find my code below and here is what I am trying to do.
My program is supposed to allocate 8 bytes of heap memory using malloc, then store the pointer from malloc to a char*, then open a file (text.txt), which contains the following lines of plain text (each 8 bytes long):
chartest
chtest2!
I am then trying to read 8 bytes at a time from text.txt using fread, until the end of file has been reached. The 8 bytes read in fread are stored in the chuck of memory allocated earlier with malloc. I am then using my char* to iterate over the 8 bytes and print each character in stdout using printf. After every 8 bytes (and until EOF) I reset my pointer to the 0th byte of my 8-byte memory chunk and repeat until EOF.
Here is the code:
int main(void)
{
char* array = malloc(8 * sizeof(char));
if (array == NULL)
return 1;
FILE* inptr = fopen("text.txt", "r");
if (inptr == NULL)
return 2;
while (!feof(inptr))
{
fread(array, 8 * sizeof(char), 1, inptr);
for (int i = 0; i < 8; i++)
{
printf("%c", *array);
array++;
}
array -= 8;
}
free(array);
fclose(inptr);
return 0;
}
Please bare in mind that the program has been run through valgrind, which reports no memory leaks. This is the output I get:
chartest
chtest2!
htest2
I don't get where the 3rd line comes from.
Moreover, I don't understand why when I reset my char pointer (array) using
array -= 7;
and running through valgrind it reports:
LEAK SUMMARY:
==8420== definitely lost: 8 bytes in 1 blocks
Logically thinking of the 8 bytes of heap memory as an array of chars we would have to take the pointer back 7 places to reach spot 0, but this approach seems to leak memory (whereas array -= 8 is fine)!
I would be very grateful if someone could analyse this. Thanks!