I have the following ANSI C code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
char *buffer = 0;
int length = 0;
FILE *f = fopen("text.txt", "r");
if(f) {
fseek(f, 0, SEEK_END);
length = ftell(f);
fseek(f, 0, SEEK_SET);
buffer = malloc(length);
fread(buffer, 1, length, f);
fclose (f);
}
printf("File size: %d\nBuffer size: %d\nContent: %s\n=END=", length, strlen(buffer), buffer);
return 0;
}
Which for some reason after the malloc alocates more memory than needed and output extra garbage from the memory, example: First run:
File size: 12 Buffer size: 22 Content: 123456789012les=$#▬rW| =END=
Second run:
File size: 12 Buffer size: 22 Content: 123456789012les↔1↕.' =END=
Third run:
File size: 12 Buffer size: 22 Content: 123456789012les=▬kπà =END=
Could someone please help me with this and also explain why my version is behaving weird? I use MingW TDM-GCC 4.9.2 32bit for compilation (gcc)