本文介绍了malloc()用于struct成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我有一个非常简单的问题,我现在对

感到有点困惑。可以通过malloc()或calloc()为

结构成员分配内存然后调用free()吗?例如,我在下面有代码




struct mystruct {

int a;

char * b;

int c;

};


struct mystruct myobject;


myobject.b =(char *)malloc(50);

....

....

免费(myobject.b);


上面的代码是好的,还是有任何潜在的问题?


谢谢!

Hello, I have a very simple question that I''m a bit confused about
right now. Is it OK to allocate memory by malloc() or calloc() for a
struct member and then call free() on it? For example, I have the code
below.

struct mystruct {
int a;
char *b;
int c;
};

struct mystruct myobject;

myobject.b = (char *)malloc(50);
....
....
free(myobject.b);

Is the above code OK, or is there any potential problem with it?

Thanks!

推荐答案




我能看到的唯一问题就是你施放了malloc()的结果。

这是合法但不必要的,可以掩盖错误。将行改为




myobject.b = malloc(50);


除此之外,我没有看错。


-

Keith Thompson(The_Other_Keith)< http://www.ghoti.net/~kst>

圣地亚哥超级计算机中心< *> < http://users.sdsc.edu/~kst>

我们必须做点什么。这是事情。因此,我们必须这样做。



The only problem I can see is that you cast the result of malloc().
This is legal but unnecessary, and can mask errors. Change the line
to

myobject.b = malloc(50);

Other than that, I don''t see anything wrong.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.




<<删除电子邮件的del>>


<<Remove the del for email>>



这篇关于malloc()用于struct成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 15:33
查看更多