[英]How to fix valgrind memory?
So I have a structure and when I initiate one, I use malloc as so: 所以我有一个结构,当我启动一个结构时,我就这样使用malloc:
typedef struct node{
void *value;
struct node *next;
} node;
typedef struct QueueADT{
int (*cmp)(const void*a, const void*b);
struct node *front;
int len;
struct node *back;
} * QueueADT;
QueueADT que_create( int (*cmp)(const void*a, const void*b) ) {
printf("%lu\n",sizeof(QueueADT));
QueueADT q = (QueueADT)malloc(sizeof(QueueADT));
if (q == NULL) {return NULL;}
q->cmp = cmp;
q->len = 0;
return q;
}
valgrind spits out: valgrind吐出:
Invalid write of size 4
Address 0x5204490 is 8 bytes after a block of size 8 alloc'd
write error pertains to q->len = 0; 写入错误与q-> len = 0有关;
I cannot tell what the problem is, am I allocating an incorrect amount of bytes? 我不知道问题出在哪里,我分配的字节数不正确吗?
It looks like QueueADT
is a typedef for a pointer type. 看起来
QueueADT
是指针类型的typedef。 That means sizeof(QueueADT)
evaluates to the size of the pointer, not what it points to. 这意味着
sizeof(QueueADT)
计算结果是指针的大小,而不是指针所指向的大小。 Since it seems that a pointer is 8 bytes on your system and that the struct in question is larger than that, you write past the end of allocated memory. 由于似乎您的系统上的指针是8个字节,并且所讨论的结构大于该字节,因此您要在分配的内存末尾写入。
What you want instead is: 您想要的是:
QueueADT q = malloc(sizeof(*q));
This allocates enough space for what q
points to. 这为
q
指向分配了足够的空间。 Also, don't cast the return value of malloc
. 另外, 不要
malloc
的返回值 。
It's also bad practice to hide a pointer behind a typedef
, as it is not obvious that you're working with a pointer which can confuse the reader, and is probably what tripped you up in this case. 将指针隐藏在
typedef
后面也是一种不好的做法,因为您使用的指针可能会使读者感到困惑,这并不是很明显,在这种情况下,这可能会让您大跌眼镜。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.