我有一个关于这个代码的问题。我在我的框架中编写了这段代码,它导致框架崩溃。但是当我在一个单独的文件中重写下面的代码时,它工作得很好。我只是想知道,下面的代码对于内存分配和释放是正确的吗?(特别是msg->context_var.type =f;部分)谢谢
#include <stdio.h>
#include <stdlib.h>
typedef struct
{
int value;
int price;
int old;
} type_t;
typedef struct {
type_t *type;
} context_t;
typedef struct {
context_t context_var;
} send_request;
void send_Message(send_request *msg)
{
type_t *f = 0;
f = malloc(sizeof(f));
msg->context_var.type = f;
msg->context_var.type->price = 1;
msg->context_var.type->value = 100;
msg->context_var.type->old =120;
printf("value of %d/n", msg->context_var.type->price);
free(f);
}
int main()
{
send_request *msg = 0;
msg = (send_request *) malloc(sizeof(send_request));
send_Message(msg);
free(msg);
return 0;
}发布于 2011-07-14 00:56:22
这是错误的。
f = malloc(sizeof(f)); /* Wrong */
f = malloc(sizeof(*f)); /* Better ? */sizeof(f)将给出您机器上指针的大小;sizeof(*f)将给出所指向的对象的大小。
根据@Perception的请求编辑
当你分配的资源少于你需要的时候,你就是在引出。任何事情都可能发生(即使是想要的行为),这完全取决于平台、环境(月相等)。
msg->context_var.type->value = 100; /* Writes beyond what's allocated. */因此,根据“框架”的内存布局,这可能只是覆盖一些内存和“工作”,或者它可能会崩溃。坦率地说,我更喜欢它直接崩溃的样子。
发布于 2011-07-14 00:59:30
您在堆上分配context_t的一个实例,然后msg->context_var.type获得结果指针f的值。
由于msg是send_Message函数的指针参数,因此在函数存在后,无法对msg及其内容做任何可靠的假设。因此,当您继续释放f指向的内存时,您会在msg->context_var.type中留下一个悬空指针。
如果它所指向的内存是在send_Message存在之后被访问的,那么您很有可能损坏了一些重要的东西(或者读取了一些疯狂的东西,比如指向0xDeadBeans的指针),因为它现在可能包含完全不同的东西。
发布于 2011-07-14 01:00:21
您不仅分配了错误的大小(参见cnicutar的答案)--如果您将f附加到框架传递的消息,您可能不希望在函数返回之前释放它。不过,您稍后需要释放它--可能是通过框架提供的其他工具?
https://stackoverflow.com/questions/6682621
复制相似问题