c - free() 崩溃,但前提是分配的内存超过一定大小

标签 c malloc free mpi

我在释放我的 mpi 程序中分配的内存时遇到一个奇怪的问题:

这是为我产生错误的代码示例:

void *out, *in;
int cnt = 2501; //if cnt<=2500: works perfectly. cnt>2500: crashes at free!

if((out = malloc(cnt * sizeof(double))) == NULL) 
    MPI_Abort(MPI_COMM_WORLD, MPI_ERR_OP);
if((in = malloc(cnt * sizeof(double))) == NULL) 
    MPI_Abort(MPI_COMM_WORLD, MPI_ERR_OP);

//Test data generation
//usage of MPI_Send and MPI_Reduce_local
//doing a lot of memcpy, assigning pointer synonyms to in and out, changing data to in and out

free(in);    //crashes here with "munmap_chunk(): invalid pointer" 
free(out);   //and here (if above line is commented out) with "double free or corruption (!prev)"

我使用 valgrind 运行它:

 mpirun -np 2 valgrind  --leak-check=full --show-reachable=yes  ./foo

得到以下内容:

==6248== Warning: ignored attempt to set SIGRT32 handler in sigaction();
==6248==          the SIGRT32 signal is used internally by Valgrind
cr_libinit.c:183 cri_init: sigaction() failed: Invalid argument

==6248== HEAP SUMMARY:
==6248==     in use at exit: 0 bytes in 0 blocks
==6248==   total heap usage: 1 allocs, 1 frees, 25 bytes allocated
==6248== 
==6248== All heap blocks were freed -- no leaks are possible
==6248== 
=====================================================================================
=   BAD TERMINATION OF ONE OF YOUR APPLICATION PROCESSES
=   EXIT CODE: 134

关于如何追踪此错误的任何想法?请注意,它仅在 cnt>2500 时出现!

最佳答案

如果您使用的是 GNU glibc,则可以在运行程序之前将环境变量 MALLOC_CHECK_ 设置为 2,以启用对内存分配调用的额外检查—详情 here .

关于c - free() 崩溃,但前提是分配的内存超过一定大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10602966/

相关文章:

c - C缓冲区溢出的解释

c++ - 错误[P​​e167] : argument of type "uint16_t *" is incompatible with parameter of type "unsigned char *"

c - 在数组中查找元素时应用程序崩溃

c - 这可能是由于堆损坏,这表明 cvector.exe 或它加载的任何 DLL 中存在错误

c - 非动态数组何时在结构中释放

c - 我正在寻找内容寻址数据结构

c - 8 位 NES 程序内存限制

c - 我需要在 getline() 失败后调用 free() 吗?

c - 在 C 中释放一棵树

windows - Windows 内核中的 free/malloc 函数