I’ve made a function that reads a file into the memory in C. But I’m having an issue with the code, random characters seem to appear at the end of the string. Even after I added ‘\0’ at the end. I don’t understand this at all since the whole file appears and I haven’t malloc’d enough room for more characters, so there should be some kind of error if there are more chars? Anyway does anyone knows what’s causing this?
char* LoadSourceFile(char* filename)
{
int fileSize;
char* buffer;
struct stat handle;
FILE* bestand;
stat(filename, &handle);
if (fopen_s(&bestand, filename, "r") != 0) {
return NULL;
}
fileSize = handle.st_size;
handle.st_size++;
buffer = (char*)malloc(handle.st_size);
if (buffer == NULL) {
return buffer;
}
fread_s(buffer, handle.st_size, fileSize, 1, bestand);
buffer[fileSize] = '\0';
fclose(bestand);
return buffer;
}
Look at the return from fread_s which is the number of bytes read to buffer. It could be less than expected.
Edit: you would have to swap the count/size parameters to make what I said correct: