[英]malloc and freeing memory between threads in C
我在不同線程之間共享一組全局變量,因此我根據需要分配多少內存,具體取決於分配給它的內存量。 有點像緩沖區。 每當我嘗試從同一線程但從不同功能中釋放它時,glib就會發瘋並造成段錯誤。
我到目前為止還不是交流程序員。 我正在嘗試清除我一起入侵的代碼中的內存泄漏。
char *keybuffer[], *valuesbuffer[], *returnbuffer[], *bufferaction;
int memcache_lock=1,*bufferelements, bufferowner=0;
void memcache_clear_buffers(){
free(&bufferaction); //I get the same reaction when I have the & and without the &
// free(*keybuffer); //I thought maybe I need to use the pointer. Then
// free(*valuesbuffer); // I thought maybe I needed to reference the address in memory.
// free(*returnbuffer); // I appreciate any help.
// free(*bufferelements);
}
void memcache_allocate_buffers(int size){
*keybuffer = (char *)malloc(size * sizeof(char *));
*valuesbuffer = (char *)malloc(size * sizeof(char *));
*returnbuffer = (char *)malloc(size * sizeof(char *));
bufferelements = malloc(sizeof(int));
bufferaction = (char *)malloc(sizeof(char*));
}
這是valgrind的輸出。
3500== Invalid free() / delete / delete[]
==3500== at 0x4027C02: free (vg_replace_malloc.c:366)
==3500== by 0x4191D4C: memcache_clear_buffers (dm_memcache.c:254)
==3500== by 0x41921ED: memcache_set (dm_memcache.c:328)
==3500== by 0x4192281: memcache_sid (dm_memcache.c:151)
==3500== by 0x418316D: db_user_exists (dm_db.c:3208)
==3500== by 0x403F7F2: auth_user_exists (authsql.c:49)
==3500== by 0x419ADA6: auth_user_exists (authmodule.c:130)
==3500== by 0x4040D4E: auth_validate (authsql.c:333)
==3500== by 0x419B106: auth_validate (authmodule.c:163)
==3500== by 0x74656CFF: ???
==3500== Address 0x41b55c0 is 0 bytes inside data symbol "bufferaction"
無效的免費怎么辦?
volatile
,以防止某些編譯器出現危險的優化器錯誤。 請注意,這不能替代互斥防護。 free(bufferaction)
,不是free(&bufferaction)
。 當您應該釋放bufferaction
(沒有“&”號)時,您正在釋放&bufferaction
我還懷疑您在使用緩沖操作時可能會損壞內存。 您會看到,您只分配了4個字節(如果要為64位平台進行編譯,則分配8個字節)。 如果您使用的內存超過了該數量,那么分配的內存將最終破壞內存。 這可能僅在釋放內存時才會顯示出來,因為您可能已經弄亂了一些內部堆結構。
我真的不認為這是與並發相關的錯誤。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.