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!
As pointed to in the comments, you are using feof incorrectly, which explains the extra line. As for subtracting 7 instead of 8: you add 1 to array 8 times, so why would you expect subtracting 7 to get you back to where you started?
I made some changes to your code and everything is working fine. Here it is :
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void)
{
char* array = malloc(9 * sizeof(char)); \\changed
if (array == NULL)
return 1;
FILE* inptr = fopen("file", "r");
if (inptr == NULL)
return 2;
while (!feof(inptr))
{
fread(array, 9 * sizeof(char), 1, inptr); \\changed
int i=0;
for (i = 0; i < 8 ; i++)
{
if(feof(inptr)) \\added
goto next; \\added
printf("%c", *array);
array++;
}
printf("\n"); \\added
next:array =array - i; \\changed
}
free(array);
fclose(inptr);
return 0;
}
You need to take care of the space allocated, the end of file EOF character and the end of line \n and for that reason your program did not work as you were expecting !!!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With