【发布时间】:2020-11-26 18:58:53
【问题描述】:
我使用以下 malloc/calloc 代码获得空内存。有时它无法为“name1”分配内存,然后 strcpy 失败。请指导。
struct testMalloc
{
char name1[90];
char name2[90];
struct testMalloc* ptr;
};
int main(int argc, char* argv[])
{
struct testMalloc* test = 0 ;
int size = 0;
size = sizeof(struct testMalloc);
printf("Size of struct is %d", size);
test = (struct testMalloc*) calloc(sizeof(struct testMalloc));
strcpy((test->name1), "hdshdssdsdfsfffffffffffffffffffffffffffffh");
return 0;
}
【问题讨论】:
-
指针不能用 0 初始化,而是用
(void*)0初始化,以防你想获得一个 NULL 指针作为值。否则它是未定义的行为。 -
@alinsoar 你确定吗?你有消息来源吗?
-
@alinsoar 事实上,C 标准委员会最终向那些相信
0ISNULL的误入歧途的程序员投降.现在实际上不是NULL,但0是符合 C 标准的空指针常量。 -
@AndrewHenle 在某些系统上我听说空指针不全为 0,但从未见过这样的系统。
-
@alinsoar
0转换为指针类型时始终为== NULL。它不必由所有位 0 表示。无论是显式转换(void *)还是仅允许它被隐式转换都没有关系。