malloc calloc 无法分配结构

0 c 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;

}
Run Code Online (Sandbox Code Playgroud)

ali*_*oar 7

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

如果您包含<stdlib.h>的代码在正确调用calloc.

  • 这就是为什么我们[不转换 `malloc` 和系列的返回值](/sf/ask/42409181/)。 (6认同)