问题描述
|
我定义了以下函数,其中List是一个结构。
List * LIST_Create()
{
List * l = calloc(0,sizeof(List));
unsigned char * pc = (unsigned char *)l;
for(i = 0; i < sizeof(List); i++)
{
LOG(\"LIST\",\"0x%1x \",(unsigned char)*pc);
pc++;
}
}
当我打印出字节时,我得到了:
LIST: 0xffffffbf
LIST: 0x1
LIST: 0x13
LIST: 0x0
LIST: 0x1
LIST: 0x1
LIST: 0x0
LIST: 0x0
LIST: 0x0
LIST: 0x0
LIST: 0x0
LIST: 0x5
这是怎么回事?我知道这不是打印问题,因为代码也正在读取非零值。我可以可靠地将List结构归零的唯一方法似乎是分别初始化所有成员。我不在乎,但是but2ѭ不应该工作吗?
解决方法
您为space3 space
List
分配了足够的空间:
List * l = calloc(0,sizeof(List));
因此,您分配的内存为3个字节长。
, calloc(0,sizeof(List))
分配一个0长度的缓冲区;您将在创建“虚拟”指针后打印随机数据,以便稍后将其“ 8”移。 calloc
的参数是项目数和单个项目的大小;例如,这使得分配5(struct foo)
s的向量更加容易。
, 该手册说:
calloc() allocates memory for an array of nmemb elements of size bytes
each and returns a pointer to the allocated memory. The memory is set
to zero. If nmemb or size is 0,then calloc() returns either NULL,or
a unique pointer value that can later be successfully passed to free().
您的函数调用List * l = calloc(0,sizeof(List));
因此,您有一个0
长度的存储块地址或l
中的NULL
。 (可能您已经和memset
混为一谈了?)
, 您正在请求分配零字节。 calloc
分配的大小为nmemb*size
,而您有nmemb == 0
。
, 您正在用0个元素(没有元素)调用calloc
。您至少必须通过1:
List* l = calloc(1,sizeof(List));