Strange behavior: same code on different locations, one fails reading binary file
I'm having trouble with a small piece of code, I'm trying to read a binary file, if I have this code on a separate file, build and run it, it reads the file perfectly, but if I put the same code on a larger project within a function, it always reads the data incorrectly (being the same file for the 2 tests).
This开发者_如何学C is the code on the separate project:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main(int argc, char* argv[]) {
char* filename = (char*)"file.binary";
FILE* file = fopen(filename, "rb");
if (!file) {
printf("Unable to open %s for reading. \n", filename);
fclose(file);
free(filename);
exit(1);
}
fseek (file , 0 , SEEK_END);
long size = ftell (file);
rewind (file);
printf("Number of bytes in the file is %ld \n", size);
int version = 0;
char* string = (char*)malloc(sizeof(char) * 3);
fread(string, sizeof(char), 3, file);
if (strcmp(string, (char*)"str")) {
printf("%s is not properly formatted. \n", filename);
fclose(file);
free(filename);
exit(1);
}
fread(&version, sizeof(int), 1, file);
printf("%s version %d\n", string, version);
free(filename);
fclose(file);
}
I'm not posting the code on the larger project because it's exactly the same (copy pasted) except because it goes inside a class function instead of directly on the main function. It is quite a simple piece of code, but for some strange reason it's failing and I can't get my head around it. The file size is being correctly read for both cases, the separate project reads the "string" and "version" data correctly and gets to print it correctly, however on the larger project it always gets into the second conditional because the string isn't what is expected to be.
I don't think it's related, but the larger project is being built into a static library which is later being used to link against from the main program.
Does anyone have a clue may I be missing? Thanks.
char* string = (char*)malloc(sizeof(char) * 3);
fread(string, sizeof(char), 3, file);
if (strcmp(string, (char*)"str")) {
}
You allocate memory for three characters, but you compare against four: "str" and the null byte. You should allocate four bytes and set the last one to zero (or simply use calloc
). I could imagine that the fourth byte indeed happens to be zero in a stand-alone application, but not within a larger project.
精彩评论