我的程序是用 C 编写的,我正在用 gcc 编译。我正在读取一个文件,并将文件的内容存储到一个缓冲区中。为此,我需要缓冲区与文件一样大。我正在使用 malloc() 为缓冲区分配内存。不幸的是,我遇到了一个 277MB 的文件。这对堆来说太多了吗?我在运行时遇到段错误,但除此之外没有更多信息。它适用于大至 160 MB 的文件,但 277MB 文件的这个单一异常值正在破坏它。
编辑:valgrind 给我
@0xC0000022L valgrind 给我
==6380== Warning: set address range perms: large range [0x8851028, 0x190e6102) (undefined)
==6380== Warning: set address range perms: large range [0x8851028, 0x190e6028) (defined)
==6380== Warning: set address range perms: large range [0x190e7028, 0x2997c108) (undefined)
==6380== Warning: set address range perms: large range [0x190e7028, 0x2997c028) (defined)
==6380== Warning: silly arg (-1737565464) to malloc()
==6380== Invalid write of size 4
==6380== at 0x8048A49: main (newanalyze.c:85)
==6380== Address 0x4a00 is not stack'd, malloc'd or (recently) free'd
==6380==
==6380==
==6380== Process terminating with default action of signal 11 (SIGSEGV)
==6380== Access not within mapped region at address 0x4A00
==6380== at 0x8048A49: main (newanalyze.c:85)
但第 85 行只是一个小变量,不应受文件大小的影响。
最佳答案
请注意Valgrind的输出,
==6380== Warning: silly arg (-1737565464) to malloc()
-1737565464是signed int值,如果是unsigned int则为2557401832(>2G)。您将 >2G 参数而不是 277M 传递给 malloc。
并且根据以下信息,我们知道您正在尝试写入地址 0x4a00,这是一个无效地址,在这种情况下您会期望一个 SEGV。请检查您的代码中的 newanalyze.c:85 以查看其中的内容。
==6380== Invalid write of size 4
==6380== at 0x8048A49: main (newanalyze.c:85)
==6380== Address 0x4a00 is not stack'd, malloc'd or (recently) free'd
关于c - 堆有多大就太大了,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11453802/