MALLOC_PERTURB_ 环境变量

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()返回的内存空间的初始值为 0x0ffree()之后的值是未知的。
基于此特性,我们可以借助 "MALLOC_PERTURB_"环境变量来调试可能存在问题的代码。

参考资料:

  1. https://udrepper.livejournal.com/11429.html
  2. https://www.gnu.org/software/libc/manual/html_node/Malloc-Tunable-Parameters.html
  3. https://www.borelly.net/cb/docs/libc/Malloc-Tunable-Parameters.html
  4. https://bugzilla.kernel.org/show_bug.cgi?id=20102
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值