使用memcpy
和空闲内存时,free
会导致堆损坏。我不明白为什么。
char *buff = malloc(20);
memset(buff,NULL,20);
strcpy(buff,"xvxvxvxxvx");
char*time = malloc(20));
memset(time,NULL,20);//memcpy use
memcpy(time,buff,20);
free(time);//crashing here
return 0;
答案 0 :(得分:5)
sizeof(20)
是int
的大小。您可能打算将malloc(20)
用于20个字符。
答案 1 :(得分:0)
memset的第二个参数需要int但是接收NULL。
void * memset(void * s,int c,size_t n);
memset()函数用常量字节c填充s指向的内存区域的前n个字节。
所以你可以使用memset作为 memset的(浅黄色,0,20); 现在程序不会崩溃。