宝慕林4294392
具体来说,myfree中的num变量在内存中紧邻着p变量,如果你将num申明为int,那他只占四个字节,而你初始化num的时候 memcpy(&num, p, sizeof(size_t)); 却会将8个字节拷进去,这会修改紧邻这num的变量p,直接导致p被清零(如果malloc free外加修改的话,清的不一定是0),而free函数在传入空指针是不做处理的。我把代码修改了一下,你可以看一下下面程序的输出,对应myfree的free那一行,实际被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;}