程序在malloc附近被击中 [英] Program getting struck near malloc
问题描述
我使用了如下代码
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);
我有185mb的文件,即file_size = 190108334字节。对于此文件,malloc崩溃了,并且程序在此阶段被执行。
如果我使用其他任何较小的文件,它都可以正常工作。
我该怎么办?
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 ?
推荐答案
您应该至少测试 fopen
成功:
fp_input = fopen(inp_path, "rb");
if (!fp_input) { popen(inp_path); exit(EXIT_FAILURE); };
您的 malloc
可能不会崩溃,但是失败(通过返回 NULL
):阅读 malloc(3)因此至少要编写代码:
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,您可能想内存映射文件。如果您使用的是Linux或Posix系统,请了解 mmap(2)(并使用 fstat(2)来查询 open(2) -ed文件描述符的大小)。 Windows还可以使用 CreateFileMapping
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
如果您的 malloc
确实是崩溃,则可能意味着您具有内存损坏(在 malloc
调用之前),因此系统的某些内部变量 malloc
被违反。使用某些内存调试器工具(例如 valgrind 或 purify 在Windows上)进行检测。
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.
这篇关于程序在malloc附近被击中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!