-1

I have use the code like below

char *es_data;

fp_input = fopen(inp_path, "rb");

fseek(fp_input, 0, SEEK_END);
file_size = ftell(fp_input);
fseek(fp_input, 0, SEEK_SET);

es_data = (char*)malloc(file_size);
fread(es_data, 1, file_size, fp_input);

I have a file of 185mb, i.e., file_size = 190108334 bytes. For this file, malloc is crashing, and program is getting struck at this stage. If i use any other file of lower size, it works fine. What can I do ?

  • check for `fp_input` being NULL and also check for `es_data` being NULL. And [don't cast malloc](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc). – M.M Jul 17 '14 at 05:02
  • First thing to do... Always check the return value of malloc(). – Mahonri Moriancumer Jul 17 '14 at 05:03
  • What is your platform? Compiler? Is this 32/64 bit? And most importantly - did you make sure the `fp_input = fopen(inp_path, "rb");` succeeded? Because if it didn't... – YePhIcK Jul 17 '14 at 05:04
  • Don't cast the result of `malloc`, it's `void*` and compatible to any pointer in `C`. Any cast can hide errors that the compiler could detect and indicate with a diagnostic messages. Further the readability gets worse with casts. – harper Jul 17 '14 at 05:09
  • `malloc` is a system function is isn't known for crashing. Is your problem that `malloc` returns a NULL pointer? Change your code to check the return value. – harper Jul 17 '14 at 05:12
  • Is program crashing (terminating) or getting stuck (becomes unresponsive but does not terminate)? – hyde Jul 17 '14 at 05:13
  • 1
    Also, check return values of all functions, especially `ftell` before giving it to `malloc`... – hyde Jul 17 '14 at 05:20

1 Answers1

1

You should test at least that fopen succeeds:

 fp_input = fopen(inp_path, "rb");
 if (!fp_input) { popen(inp_path); exit(EXIT_FAILURE); };

Your malloc is probably not crashing, but failing (by returning NULL): read malloc(3) so code at least:

 es_data = malloc(file_size);
 if (!es_data) { perror("malloc"); exit(EXIT_FAILURE); }

BTW, you probably want to memory map a file. If you are on Linux or a Posix system, learn about mmap(2) (and use fstat(2) to query the size of an open(2)-ed file descriptor). Windows can also memory map a file with CreateFileMapping

If your malloc is indeed crashing this probably means that you have memory corruption (before that malloc call) so some internal invariant of your system malloc is violated. Use some memory debugger tool (like valgrind on Linux, or purify on Windows) to detect it.

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547