首页 > 解决方案 > malloc calloc 分配结构失败

问题描述

我使用以下 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;

}

标签: cmalloccalloc

解决方案


您不包括<stdlib.h>让编译器知道的签名,calloc在这种情况下它使用K&R调用约定。

如果您包含<stdlib.h>代码之前将无法编译以正确调用calloc.


推荐阅读