除非以前已分配(并释放),否则可以将功能的结构指针引用
我应该对代码进行长时间的解释,但是解释已经在下面的代码中,所以我想我的问题是:如何使它起作用而无需杂乱然后释放它?还是基本上,在这种情况下写这篇文章的正确方法是什么?
#include <stdio.h>
#include <malloc.h>
struct d {
int f;
};
struct d* rr() {
struct d* p = malloc(sizeof (struct d*));
p->f = 33;
return p;
}
void rr2(struct d* p) {
p = malloc(sizeof (struct d*));
p->f = 22;
}
int main()
{
//works..
struct d* g;
g = malloc(sizeof (struct d));
g->f = 45;
printf("[%i]", g->f);
//works..
g = rr();
printf("[%i]", g->f);
//below, both are same, except in this first case, g is allocated then freed..
//works..
free(g);
rr2(g);
printf("[%i]", g->f);
//doesn't work..
struct d *q;
rr2(q);
printf("[%i]", q->f);
return 0;
}
I supposed to write a long explanation of the code but the explanation is already in the code below so I guess my question is: How do I get it to work without having to malloc then freeing it? or basically what is the correct way to write this in a situation like this?
#include <stdio.h>
#include <malloc.h>
struct d {
int f;
};
struct d* rr() {
struct d* p = malloc(sizeof (struct d*));
p->f = 33;
return p;
}
void rr2(struct d* p) {
p = malloc(sizeof (struct d*));
p->f = 22;
}
int main()
{
//works..
struct d* g;
g = malloc(sizeof (struct d));
g->f = 45;
printf("[%i]", g->f);
//works..
g = rr();
printf("[%i]", g->f);
//below, both are same, except in this first case, g is allocated then freed..
//works..
free(g);
rr2(g);
printf("[%i]", g->f);
//doesn't work..
struct d *q;
rr2(q);
printf("[%i]", q->f);
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
对于两个功能中的初学者
,
都有错别字。看来您的意思
和
或
与
此功能有关
,然后在此调用中,
指针
q
通过值传递给该函数。因此,该功能处理指针Q
的副本。更改函数中的副本不会反映原始指针Q
。它保持不变。要使代码正常工作,您必须通过参考将指针传递(通过指向其指针间接传递)。在这种情况下,该函数将看起来像
和称为
此代码段
,然后将其调用不确定的行为,因为在此语句中,
可以访问已经释放的内存。
For starters in the both functions
and
there is a typo. It seems you mean
and
or
and
As for this function
then in this call
the pointer
q
is passed to the function by value. So the function deals with a copy of the pointerq
. Changing the copy within the function does not reflect on the original pointerq
. It stays unchanged.To make the code working you have to pass the pointer by reference (indirectly through a pointer to it). In this case the function will look like
and be called like
As for this code snippet
then it just invokes undefined behavior because in this statement
there is an access to already freed memory.