473,946 Members | 17,657 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

malloc() for struct member

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!

Nov 15 '05 #1
10 4050
"googler" <pi********@yah oo.com> writes:
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?


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_Keit h) 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.
Nov 15 '05 #2
On 5 Oct 2005 20:06:15 -0700, "googler" <pi********@yah oo.com> wrote:
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);
Don't cast the return from malloc. It doesn't help and may cause the
compiler to suppress a diagnostic you really want to see....
...
free(myobject. b);
This is how you would avoid a memory leak. What prompted the
question?

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

Thanks!

<<Remove the del for email>>
Nov 15 '05 #3
> What prompted the question?

A code like the one I gave resulted in a crash. That's why I posted the
question. My main point was if allocating and freeing memory is OK when
done on a struct member (I knew it's OK, but the above crash made me a
bit confused).

I presume it's a compilation problem since the release build works and
the crash happens for debug build (which is weird since it is usually
the other way round).

Nov 15 '05 #4
"googler" <pi********@yah oo.com> wrote in message
news:11******** **************@ o13g2000cwo.goo glegroups.com.. .
[snip]
I presume it's a compilation problem since the release build works and
the crash happens for debug build (which is weird since it is usually
the other way round).


I agree it is usually the other way round, but the same still applies: the
difference is most likely due to undefined behaviour.

Alex
Nov 15 '05 #5
Alex Fraser wrote:
"googler" <pi********@yah oo.com> wrote in message
news:11******** **************@ o13g2000cwo.goo glegroups.com.. .
[snip]
I presume it's a compilation problem since the release build works and
the crash happens for debug build (which is weird since it is usually
the other way round).


I agree it is usually the other way round, but the same still applies: the
difference is most likely due to undefined behaviour.


To expand on what Alex said (which I agree with), I would strongly
suggest that you track down and fix the bug. It might not be causing a
crash in the release build, but it could well be corrupting something
under some conditions leading to incorrect results, for example raising
millions of invoices for 139.90 instead of 149.90 and loosing some
company lots of money. Or you might be lucky and it crashes on your
customers instead of corrupting their vital data.
--
Flash Gordon
Living in interesting times.
Although my email address says spam, it is real and I read it.
Nov 15 '05 #6
KJ

googler wrote:
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); As Every Body Said Not Need To Type Cast. ...
...
free(myobject.b );

Is the above code OK, or is there any potential problem with it? The code doesn't seems to have problem. But since i m not sure the
whole code is there or not so it could be some other reason.
Thanks!


Nov 15 '05 #7
googler wrote:

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?


The above is no different than:

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

(Aside from the removal of the unnecessary, and sometimes problematic,
cast of malloc's return.)

The fact that the place you store the pointer is within a struct has
no bearing on how malloc/free work.

--
+-------------------------+--------------------+-----------------------------+
| Kenneth J. Brody | www.hvcomputer.com | |
| kenbrody/at\spamcop.net | www.fptech.com | #include <std_disclaimer .h> |
+-------------------------+--------------------+-----------------------------+
Don't e-mail me at: <mailto:Th***** ********@gmail. com>
Nov 15 '05 #8
Thanks everybody for the help.
myobject.b = (char *)malloc(50);

As Every Body Said Not Need To Type Cast.


Doesn't K&R use type cast with malloc()? Maybe it's not a good
practice, but I'm wondering that in almost all C codes I've seen, type
cast has been used with malloc().

Nov 15 '05 #9
"googler" <pi********@yah oo.com> writes:
Thanks everybody for the help.
> myobject.b = (char *)malloc(50);

As Every Body Said Not Need To Type Cast.


Doesn't K&R use type cast with malloc()? Maybe it's not a good
practice, but I'm wondering that in almost all C codes I've seen, type
cast has been used with malloc().


Yes, but the errata list at
<http://cm.bell-labs.com/cm/cs/cbook/2ediffs.html> corrects it:

142(6.5, toward the end): The remark about casting the return
value of malloc ("the proper method is to declare ... then
explicitly coerce") needs to be rewritten. The example is correct
and works, but the advice is debatable in the context of the
1988-1989 ANSI/ISO standards. It's not necessary (given that
coercion of void * to ALMOSTANYTYPE * is automatic), and possibly
harmful if malloc, or a proxy for it, fails to be declared as
returning void *. The explicit cast can cover up an unintended
error. On the other hand, pre-ANSI, the cast was necessary, and it
is in C++ also.

--
Keith Thompson (The_Other_Keit h) 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.
Nov 15 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

10
2292
by: Christof Krueger | last post by:
Hello, I'm quite new to C++ and have some base C knowledge. So I know how to solve a given problem, by I sometimes tend to fall back to C. That is what I want to avoid in my current project. Therefore I have the following question: I maintain a list of objects that are created. There is some information that is logically related to each instance. I encapulate this in a struct like this:
36
7815
by: Bhalchandra Thatte | last post by:
I am allocating a block of memory using malloc. I want to use it to store a "header" structure followed by structs in my application. How to calculate the alignment without making any assumption about the most restrictive type on my machine? Thanks.
29
40456
by: David Hill | last post by:
Is there a difference between: /* code 1 */ struct sample test; test = malloc(sizeof(struct sample)); memset(&test, 0, sizeof(test)); /* code 2 */ struct sample test; test = calloc(1, sizeof(struct sample));
34
6473
by: Richard Hunt | last post by:
I'm sorry for asking such a silly question, but I can't quite get my head around malloc. Using gcc I have always programmed in a lax C/C++ hybrid (which I suppose is actually c++). But I have started messing around in Plan 9, and that sort of thing is totally no go there :). Is this correct to allocate memory for my struct? It works on my computer, but I'm suspicious that I'm doing it wrong. --
7
2234
by: Rano | last post by:
/* Hello, I've got some troubles with a stupid program... In fact, I just start with the C language and sometime I don't understand how I really have to use malloc. I've readden the FAQ http://www.eskimo.com/~scs/C-faq/faq.html but it doesn't seem to answer my questions... So, I've made an example behind, with some included questions...
58
3966
by: lasek | last post by:
Hi all..i'm here another time..for a simple question: #include <stdlib.h> #include <stdio.h> int main(void) { /* ** I know that someone else use different malloc ** instruction
3
550
by: Kurt | last post by:
Hi all, I know there's been a lot of articles and posts because of this malloc and free combination and I've read quite a lot of them. Still I can't get my program to work: My Structure: typedef struct rule { char ip; struct rule *next;
25
3413
by: jbholman | last post by:
I am pretty new to C and doing my first project in C. I actually read almost the entire FAQ, but can't seem to figure out this problem. I have a structure. I have a list of these structures. Inside each structure, I have two members: a list of strings, and a string. I have made a sample program below that exhibits the error I am having. I also read about Valgrind, and used it to tell me where I was getting the segmentation fault,...
2
11954
by: hal | last post by:
Hi, I'm trying to make an array of pointers to 'TwoCounts' structs, where the size of the array is arraySize. Right now I'm just mallocing enough space for all the pointers to the structs, and mallocing space for the pointer 'countPtr' in each struct, but do I need to do anything else? Thanks. typedef struct TwoCounts { int *countPtr;
0
9981
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
11566
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
11153
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
11337
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9886
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
8253
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6112
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
6331
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
4533
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.