473,395 Members | 2,795 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

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 3997
"googler" <pi********@yahoo.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_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.
Nov 15 '05 #2
On 5 Oct 2005 20:06:15 -0700, "googler" <pi********@yahoo.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********@yahoo.com> wrote in message
news:11**********************@o13g2000cwo.googlegr oups.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********@yahoo.com> wrote in message
news:11**********************@o13g2000cwo.googlegr oups.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********@yahoo.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_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.
Nov 15 '05 #10
After you free the memory, set the member variable to NULL and see if that
changes anything.

When you start getting weird errors/crashes, it's usually worthwhile to look
for buffer overruns, freeing memory that has already been freed, and things
like that.

--
---------------------------------------------------------------------
DataGet & PocketLog www.dataget.com
Data Collectors www.baxcode.com
--------------------------------------------------------------------

"googler" <pi********@yahoo.com> wrote in message
news:11**********************@o13g2000cwo.googlegr oups.com...
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 #11

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

Similar topics

10
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....
36
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...
29
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,...
34
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...
7
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...
58
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
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:...
25
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. ...
2
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...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
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,...
0
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...
0
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,...

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.