自定義mynew和myfree函數(shù),如果myfree函數(shù)中num 的類型為int,在運(yùn)行過(guò)程中,ps aux看到程序的RSS一直增加(不降下來(lái)),存在內(nèi)存泄漏。如果myfree函數(shù)中num的類型為size_t,那么RSS就不會(huì)增加PS:機(jī)器是64位的,sizeof(size_t)=8位,sizeof(int)=4位void* mynew(size_t sz){void* p = malloc(sizeof(size_t) + sz) ;memcpy(p, &sz, sizeof(size_t));pthread_mutex_lock(&mutex);mCnt += sz + sizeof(size_t);printf("malloc sz[%d], mCnt[%d], fCnt[%d]\n", sz+sizeof(size_t), mCnt, fCnt);pthread_mutex_unlock(&mutex);return p+sizeof(size_t);}void myfree(void* prt){void* p = prt - sizeof(size_t);if (p == NULL){printf("pbuf is NULL\n");return ;}size_t num = 0;memcpy(&num, p, sizeof(size_t));pthread_mutex_lock(&mutex);fCnt += num + sizeof(size_t);printf("free sz[%d], fCnt[%d], mCnt[%d]\n", num, fCnt, mCnt);pthread_mutex_unlock(&mutex);free(p);}
1 回答

寶慕林4294392
TA貢獻(xiàn)2021條經(jīng)驗(yàn) 獲得超8個(gè)贊
具體來(lái)說(shuō),myfree中的num變量在內(nèi)存中緊鄰著p變量,如果你將num申明為int,那他只占四個(gè)字節(jié),而你初始化num的時(shí)候 memcpy(&num, p, sizeof(size_t)); 卻會(huì)將8個(gè)字節(jié)拷進(jìn)去,這會(huì)修改緊鄰這num的變量p,直接導(dǎo)致p被清零(如果malloc free外加修改的話,清的不一定是0),而free函數(shù)在傳入空指針是不做處理的。我把代碼修改了一下,你可以看一下下面程序的輸出,對(duì)應(yīng)myfree的free那一行,實(shí)際被free的是空指針。
#include <stdio.h> #include <malloc.h> #include <pthread.h> #include <unistd.h> int fCnt = 0, mCnt = 0; pthread_mutex_t mutex; void *mynew( size_t sz) { void *p = malloc ( sizeof ( size_t ) + sz); memcpy (p, &sz, sizeof ( size_t )); pthread_mutex_lock(&mutex); mCnt += sz + sizeof ( size_t ); printf ( "malloc sz[%d], mCnt[%d], fCnt[%d]\n" , sz + sizeof ( size_t ), mCnt, fCnt); pthread_mutex_unlock(&mutex); return p + sizeof ( size_t ); } void myfree( void *prt) { void *p = prt - sizeof ( size_t ); if (p == NULL) { printf ( "pbuf is NULL\n" ); return ; } int num = 0; // error! // size_t num = 0; printf ( "%p, %p\n" , &p, &num); memcpy (&num, p, sizeof ( size_t )); pthread_mutex_lock(&mutex); fCnt += num + sizeof ( size_t ); printf ( "free sz[%d], fCnt[%d], mCnt[%d]\n" , num, fCnt, mCnt); pthread_mutex_unlock(&mutex); printf ( "try to free %p\n" , p); free (p); } int main() { void *p = mynew(100); printf ( "p is %p\n" , p); myfree(p); usleep(1000000); return 0; } |
添加回答
舉報(bào)
0/150
提交
取消