是否可以像这样编写c malloc函数代码
Is it possible to write c malloc function code like this
在堆上分配内存感到困惑?
如果我像这样编写以初始化堆内存中的变量
((struct node*)malloc(sizeof(struct node)).data=2
我可以这样写而不是使用指针吗? 如果我声明节点类型变量,那么是否可以这样编写或不这样做? 如果我不通过访问直接地址使用指针。
是的,当然是可能的:
#include <stdlib.h>
struct a
{
int a;
float b;
};
void *foo()
{
void *v;
((struct a *)malloc(sizeof(struct a))) -> b = 4.0f;
(*((struct a *)malloc(sizeof(struct a)))).b = 6.0f;
*((struct a *)malloc(sizeof(struct a))) = (struct a){5, 8.0f};
((struct a *)(v = malloc(sizeof(struct a)))) -> b = 4.0f;
return v;
}
https://godbolt.org/z/suW4sp
你的问题的答案取决于你对"可能"的定义。
编写和编译这样的代码肯定是可能的,它将是一个正确的c程序,但它不会有任何意义,因为你从来没有存储过你刚刚写入的数据的实际地址,所以你没有办法在以后的程序中使用它。每次调用malloc
函数时,它都会返回新分配的内存区域的新地址,因此每次您尝试像这样访问数据时,它都会是具有不同地址的不同数据。
因此,如果要动态分配struct node
并在程序中进一步使用它,则必须像这样编写它:
struct node* tmp = (struct node*)malloc(sizeof(struct node));
tmp->data = 2;
然后,您可以将该tmp
指针用于适合您需求的任何内容。
此外,当您不再需要此数据时,不要忘记使用free
取消分配它。
相关文章:
- 是否可以像这样编写c malloc函数代码
- 如果普通默认构造函数不执行任何操作,为什么我们不能使用 malloc 创建平凡可构造的对象?
- 在C++中调用 malloc() 与"operator new"函数之间的实现差异
- 在使用新操作员和C 中的结构的调用构造函数时,获得内存损坏(Malloc)
- 是否有理由使用 malloc 初始化构造函数中的指针
- 无法调用使用 malloc/placement new 创建的类上的虚函数
- Turbo C++:为 malloc 函数生成目标代码
- 构造函数中的 Malloc 在通过 New 调用时返回 NULL
- 为什么在malloc中没有调用构造函数
- 更改 malloc 函数分配空间
- C++ 中的 malloc 和构造函数
- malloc函数的分段错误
- 当退出 new/malloc 函数时,从 new/malloc 返回的指针如何保持在范围内
- 当动态分配数组的函数被多次调用时,malloc 出错
- 在模板化类的构造函数中使用 malloc
- 如何使用 calloc/malloc 等函数对动态创建的存储进行正确排序,使其以 FIFO 方式运行
- malloc/new在函数指针内失败
- malloc.c:3097: sYSMALLOc:断言在动态创建的对象的构造函数中失败
- main()或任何其他函数之外的Malloc(即在全局范围内)
- 期望malloc函数的大小不同