Search code examples
cdynamic-memory-allocation

Program getting struck near malloc


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 ?


Solution

  • 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.