gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 03:06:38 25 4
gpt4 key购买 nike

我在释放我的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com