malloc()
的 man
手册上说,它返回的内存是未初始化的:
The malloc() function allocates size bytes and returns a pointer to the allocated memory. The memory is not initialized. If size is 0, then malloc() returns either NULL, or a unique pointer value that can later be success-fully passed to free().
使用未经初始化的内存空间很容易导致程序 crash
,因此,libc
提供了一个 "MALLOC_PERTURB_"
环境变量,用来指定 malloc()
函数返回的内存空间的初始值。我没有找到比较权威的文档,但结合现有的资料和测试结果可知,假设:我们设定 "MALLOC_PERTURB_"
环境变量的取值为 x
,则,malloc() 函数返回的内存空间的初始值为:(x ^ 0xFF) & (0xFF)
。示例程序如下:
#include <stdio.h>
#include <stdlib.h>
void dump_array(unsigned char *array, int len)
{
int i = 0;
for (i = 0; i < len; ++i)
printf("%02x ", array[i]);
printf("\n");
}
int main(void)
{
int size = 10;
unsigned char *array = NULL;
array = malloc(sizeof(unsigned char) * size);
if (array == NULL) {
perror("malloc failed");
return -1;
}
dump_array(array, size);
free(array);
dump_array(array, size);
return 0;
}
运行结果如下:
$ gcc -o main ./main.c
$ MALLOC_PERTURB_=0xf0 ./main
0f 0f 0f 0f 0f 0f 0f 0f 0f 0f
00 00 00 00 00 00 00 00 10 c0
$ MALLOC_PERTURB_=0xf0 ./main
0f 0f 0f 0f 0f 0f 0f 0f 0f 0f
00 00 00 00 00 00 00 00 10 10
$ MALLOC_PERTURB_=0xf0 ./main
0f 0f 0f 0f 0f 0f 0f 0f 0f 0f
00 00 00 00 00 00 00 00 10 60
可以看到, 当指定 "MALLOC_PERTURB_=0xf0"
后,malloc()
返回的内存空间的初始值为 0x0f
,free()
之后的值是未知的。
基于此特性,我们可以借助 "MALLOC_PERTURB_"
环境变量来调试可能存在问题的代码。
参考资料: