作者:拾味馆南湖店微博_328 | 来源:互联网 | 2023-09-10 17:39
I have a struct for a 2D LinkedList I'm making:
我有一个2D LinkedList的结构我正在制作:
struct Node
{
void *data;
struct Node *up, *left, *right, *down;
};
Since I'm used to Java, I made a function which pretends to be a constructor which looks like:
因为我已经习惯了Java,所以我创建了一个假装成构造函数的函数,它看起来像:
struct Node* buildNode(void *data)
{
struct Node *node = malloc(sizeof(struct Node*)); // Program crashes here.
node->data = data;
node->up = NULL;
node->left = NULL;
node->right = NULL;
node->down = NULL;
return node;
}
My program crashes when it reaches the malloc
line in the second paragraph. If I remove the *
from the malloc(sizeof(struct Node*))
, it does not crash and works correctly.
当程序到达第二段中的malloc行时,我的程序崩溃了。如果我从malloc(sizeof(struct Node *))中删除*,它不会崩溃并且可以正常工作。
Why is this? My buildNode
function is simply returning a pointer to a Node
, and is not actually returning the Node
struct itself. The error I get has something to do with corrupt heap and since I am somewhat new to C, I don't understand what this all means.
为什么是这样?我的buildNode函数只是返回一个指向Node的指针,并没有实际返回Node结构本身。我得到的错误与腐败堆有关,因为我对C有点新,我不明白这一切意味着什么。
thanks!
谢谢!
1 个解决方案
9
This line:
这一行:
struct Node *node = malloc(sizeof(struct Node*));
is allocating a memory block of pointer size (4 or 8 bytes depending on whether you're building in 32 or 64 bit mode), and returning a pointer to it. This is not what you want.
正在分配一个指针大小的内存块(4或8个字节,具体取决于你是在32位还是64位模式下构建),并返回一个指向它的指针。这不是你想要的。
Attempting to access members of the returned object results in undefined behavior, such as a crash, as the memory you're hitting is outside the bounds of the allocated space. You might also silently corrupt the heap, so that later calls to malloc
result in a crash.
尝试访问返回对象的成员会导致未定义的行为,例如崩溃,因为您正在命中的内存超出了已分配空间的范围。您也可能默默地破坏堆,以便稍后调用malloc会导致崩溃。
Whereas:
鉴于:
struct Node *node = malloc(sizeof(struct Node));
is allocating a block of memory of size of struct Node
- which is what you want.
正在分配一个大小为struct Node的内存块 - 这就是你想要的。
As an aside, you should probably be checking the returned pointer isn't NULL
before using it, then gracefully handle the error. A NULL
would be returned if the allocation fails, for example, if you run out of memory.
顺便说一句,你应该在使用之前检查返回的指针是否为NULL,然后正常处理错误。如果分配失败,将返回NULL,例如,如果内存不足。
Note also that C is (unlike Java) not a garbage collected language. You need to ensure that at some point you call free
on every pointer you allocate, or the memory will not be released until the program terminates.
另请注意,C(与Java不同)不是垃圾收集语言。您需要确保在某些时候在您分配的每个指针上调用free,或者在程序终止之前不会释放内存。