我所做的:
我在malloc(struct Node *)的参数中添加了一个指针,通常是malloc(struct Node)。
问题:
当我为指针的大小分配内存时,代码是如何工作的?
malloc()正在分配8字节内存并返回指针struct Node
{
int data;
struct Node *next;
};
struct Node *GetNode(int data)
{
struct Node *node = (struct Node *)malloc(sizeof(struct Node *));
node->data = data;
node->next = NULL;
return node;
}大小差异:
我知道malloc正在分配不同的大小,因为我这样做了
#include <stdio.h>
#include <stdlib.h>
struct Node
{
int data;
struct Node *next;
};
void main(){
int i = sizeof(struct Node);
int j = sizeof(struct Node *);
printf("%d,%d", i, j);
}输出
16,8发布于 2022-10-09 15:27:20
你所做的是未定义的行为。它可以工作(在某些系统上,在一周中的某些日子),或者它可能崩溃,或者它可能在看似无关的计算中产生错误的结果。
想象一下,你为你的卡车租了一个车库空间,但为了省钱,你需要一辆车的空间。当你开着卡车进去时会发生什么?也许它适合,也许你毁了卡车,也许你毁了车库。
所以不要这样做,为了帮助你发现你犯过类似错误的案例,可以用地址消毒软件来构建。当您以无效方式访问内存时,它将进行日志记录。
发布于 2022-10-09 20:56:13
UB是个变幻无常的情妇。有时令人愉快;有时不愉快。
这就是为什么您应该使用一种语法来减少出错的可能性:
struct Node *node = (struct Node *)malloc(sizeof(struct Node *)); // bad
struct Node *node = malloc( sizeof *node ); // good没有铸造,也没有冗余。
我甚至建议使用ty胡枝子将自己从"struct,struct,struct“中解放出来。
typedef struct s_node
{
int data; // use more indentation, please. whitespace is cheap.
struct s_node *next;
} Node_t;
/* ... */
Node_t *node = malloc( sizeof *node ); // better最后,很多小时都被浪费在追踪出现和消失的bug上。在性能成为您理解的真正问题之前,我建议使用calloc()作为进入分配函数:
Node_t *node = calloc( 1, sizeof *node ); // best您可以更容易地睡眠,知道字节值将是可重复的从运行到运行。
https://stackoverflow.com/questions/74006028
复制相似问题