我使用以下 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;
}
Run Code Online (Sandbox Code Playgroud)
您不包括<stdlib.h>让编译器知道 的签名,calloc在这种情况下它使用K&R调用约定。
如果您包含<stdlib.h>的代码在正确调用calloc.