Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
159 views
in Technique[技术] by (71.8m points)

c - 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 ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...