编译及运行结果:
<span style="">gcc -Wall malloc_1.c -o malloc_1 && ./malloc_1 p[0] no_value: address is 0x9e7f008 p[1] no_value: address is 0x9e7f009 p[2] no_value: address is 0x9e7f00a p[3] no_value: address is 0x9e7f00b p[4] no_value: address is 0x9e7f00c </span>
由程序知,存在栈中的局部指针变量指向堆中一大小为N * sizeof(char)字节的内存,并没有对这段内存进行初始化(指定存的字符)。从运行结果来看,使用malloc函数分配的内存的初始(p[i])不定(当使用malloc为int、float分配空间时,p[i]的为0,0.000000),为相应数据分配的地址连续(char型数据占一个字节,内存以一个存储单元(字节)编址)。
当把程序中memset(p, '1', N * sizeof(char))前的注释符去掉时,再次编译运行的结果为:
<span style=""> gcc -Wall malloc_1.c -o malloc_1 && ./malloc_1 p[0] no_value:1 address is 0x852b008 p[1] no_value:1 address is 0x852b009 p[2] no_value:1 address is 0x852b00a p[3] no_value:1 address is 0x852b00b p[4] no_value:1 address is 0x852b00c </span>
可见,为了避免用malloc函数申请的空间未初始化就使用后带来的错误,可用memset()函数对每个字节初始化。
注意:程序中char类型数据只占据一个字节的内存,故数据输出与初始化一样。calloc()函数calloc()函数倘若别的数据类型(如int)占多个字节(4个),则要按照二进制高地位排列得到整个int的
例memset_1.c
将malloc_1.c中char用int换掉,并把memset(p, '1', N * sizeof(char))中的参数'1'改为1(参数char要换位int),将printf("p[%d] no_value:%c\taddress is %p\n", i, p[i], &p[i]);中的%c换位%x.
编译运行:
<span style="">gcc -Wall memset_1.c -o memset_1 && ./memset_1 p[0] no_value:1010101 address is 0x90b8008 p[1] no_value:1010101 address is 0x90b800c p[2] no_value:1010101 address is 0x90b8010 p[3] no_value:1010101 address is 0x90b8014 p[4] no_value:1010101 address is 0x90b8018 </span>
本文来自电脑杂谈,转载请注明本文网址:
https://www.pc-fly.com/a/jisuanjixue/article-31017-2.html
也是醉