Program getting struck near malloc

半腔热情 提交于 2020-01-26 03:55:08

问题


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 ?


回答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.



来源:https://stackoverflow.com/questions/24795178/program-getting-struck-near-malloc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!