c-Malloc calloc无法分配结构



我使用以下malloc/caloc代码获得空内存。有时它无法为"0"分配内存;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;
}

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

如果包含<stdlib.h>,代码在正确调用calloc之前不会编译。

calloc有两个参数:元素的数量和每个元素的大小。它将把分配的内存清零。您要寻找的是malloc,它只需要一个参数:分配的内存块的总大小,并且它不会将分配的内存清零。

  1. 始终检查malloc的结果
  2. 使用sizeof中的对象而不是类型
  3. 尝试使用更安全版本的字符串函数(在本例中,传递的字符串比数组长
  4. 您不必强制转换malloc的结果,这被认为是一种糟糕的做法(现在已经过时了,但无论如何(
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct testMalloc
{
char name1[20];
char name2[90]; 
struct testMalloc* ptr;
};
struct testMalloc *allocAndCopy(const char *str)
{
struct testMalloc *ptr = malloc(sizeof(*ptr));
if(ptr)
{
strncpy(ptr -> name1, str, sizeof(ptr -> name1));
ptr -> name1[sizeof(ptr -> name1) - 1] = 0;
}
return ptr;
}

int main(int argc, char* argv[])
{
struct testMalloc* test = allocAndCopy("hdshdssdsdfsfffffffffffffffffffffffffffffh");
if(test) printf("the string is: %sn", test -> name1);
}

https://godbolt.org/z/zjvvYW

有一些语法错误:

  1. struct testMalloc* test = NULL;这就是初始化NULL指针的方式
  2. calloc(sizeof(struct testMalloc));传递给calloc的参数太少。正确的形式是calloc(no_of_elements, sizeof(type));

以下是代码的正确实现:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct testMalloc
{
char name1[90];
char name2[90]; 
struct testMalloc* ptr;
};
int main(int argc, char* argv[])
{
struct testMalloc* test = NULL;
size_t size = sizeof(struct testMalloc);
printf("Size of struct is %ldn", size);
if((test = (struct testMalloc*)calloc(1, size)) == NULL){
return -1; //Failed to allocate memory
}
else {
strcpy((test->name1),"hdshdssdsdfsfffffffffffffffffffffffffffffh");
printf("%sn",test->name1);
}

return 0;
}

从上到下:

1

您忘记使用#include stdlib.h来使用calloc()malloc()。自C99以来,禁止隐式声明。

2

int main(int argc, char* argv[])

你的程序不需要在其中加入参数。

此:

int main (void)

会更合适。

3

int size = 0;

size不应具有负值。因此,将其声明为unsigned int或更好的size_t会更合适。

4

struct testMalloc* test = 0 ; 

可以使用0初始化指针。它完全有效,因为0空指针常量。但在处理指针时最好使用NULL,而不是0,以显示指针意图并增加可读性。

struct testMalloc* test = NULL; 

5

calloc(sizeof(struct testMalloc)); 

malloc相比,calloc需要两个自变量。第一个需要是项目的数量,第二个需要是一个项目的大小。

calloc(sizeof(1,struct testMalloc)); 

6

test = (struct testMalloc*) calloc(sizeof(struct testMalloc)); 

您不需要强制转换malloc()calloc()的返回值。

  • 我是否投射malloc的结果

7

如果分配失败,您忘记检查calloc()返回的指针是否为空指针。始终检查内存管理功能的返回值。

test = calloc(1, sizeof(struct testMalloc)); 
if (test == NULL)
{
fputs("Allocation failed!", stderr);
// error routine.
}

最新更新