A function that reads file streams and prints them on-screen invokes undefined behavior and I am unable to localize the cause. This works if file, that contains less then two lines is loaded, otherwise it crashes.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <inttypes.h>
char *getText (FILE* fp)
{
uint_64 size;
uint_64 i = 0;
int chr;
char *source;
fseek(fp, 0L, SEEK_END);
size = ftell(fp);
source = calloc(size + 1, sizeof(char));
fseek(fp, 0, SEEK_SET); // rewind
while(chr != EOF)
source[i++] = (chr = fgetc(fp));
source[size] = '\0'; // Terminate string
return(source);
}
int main(void)
{
char sfile [256];
FILE* fp;
char *file;
char buff [256];
printf("Enter name of file: ");
scanf("%s", sfile);
if(!strncmp(sfile, "read-", strlen("read-")))
{
fp = fopen(sfile + strlen("read-"), "r");
file = getText(fp);
sprintf(buff, file);
printf(buff);
fclose(fp);
free(file);
}
return 0;
}