473,657 Members | 2,598 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

malloc and free

This is my first posting, please excuse me if it is off-topic.

I'm learning to program in C. It's been almost ten years I've been
programming and a lot of things have changed apparently.

I understand from other postings that casting a result from malloc
isn't good. In the past I have always been casting the malloc. I
think it was even necessary. (But that's a long time ago, I hadn't
heard of a standard for C these days). Was it really necessary or did
we do it only to silence the warnings ? (cfr. FAQ q7.7 - I can't
look in the manuals from these days : I don't have them any longer)
When I use malloc for the allocation of a small piece of memory, e.g.
a single node of a linked list, I use 'free' to release the memory
afterwards. When using 'free', I don't have to worry about the size
of the allocated block the pointer is pointing to.
Is it the operating-system that is responsible to remember the size of
that piece of memory ?
In that case, when I build a large linked-list by allocating memory
for each node, I get a lot of overhead in the operating system. Is
this right ? or is this implementation-specific or operating-system
specific ? (FAQ q7.26 says that the implementation 'remembers' the
size. Does this mean that every implementation may do it in his own
way ? )
If the computer has to remember for each single allocation the size of
the allocated block, is it better than, to allocate a bigger piece of
memory and keep track of the use of it within the program, when I try
to create a linked-list or a binary tree or something like that ?

Thank you.
Joris Adriaenssens
Nov 14 '05 #1
42 2162
On 6 Sep 2004 08:39:00 -0700, jo************* ***@hotmail.com (Joris
Adriaenssens) wrote:
This is my first posting, please excuse me if it is off-topic.

I'm learning to program in C. It's been almost ten years I've been
programming and a lot of things have changed apparently.

I understand from other postings that casting a result from malloc
isn't good. In the past I have always been casting the malloc. I
think it was even necessary. (But that's a long time ago, I hadn't
heard of a standard for C these days). Was it really necessary or did
we do it only to silence the warnings ? (cfr. FAQ q7.7 - I can't
look in the manuals from these days : I don't have them any longer)
Things change over time. The cast became unnecessary when malloc
started returning void*.

Using a cast to silence a warning is a common but not foolproof
technique. The compiler is free to give any (superfluous) diagnostic
it likes as long as it correctly compiles a conforming program.


When I use malloc for the allocation of a small piece of memory, e.g.
a single node of a linked list, I use 'free' to release the memory
afterwards. When using 'free', I don't have to worry about the size
of the allocated block the pointer is pointing to.
Is it the operating-system that is responsible to remember the size of
that piece of memory ?
It is an implementation responsibility. Whether that falls on the
operating system of the C run-time library is an implementation issue.
In that case, when I build a large linked-list by allocating memory
for each node, I get a lot of overhead in the operating system. Is
"lot" is a matter of opinion. Some operating systems may do this so
efficiently that the amount of overhead is not unacceptable *to you*.
this right ? or is this implementation-specific or operating-system
specific ? (FAQ q7.26 says that the implementation 'remembers' the
size. Does this mean that every implementation may do it in his own
way ? )
Yes
If the computer has to remember for each single allocation the size of
the allocated block, is it better than, to allocate a bigger piece of
memory and keep track of the use of it within the program, when I try
to create a linked-list or a binary tree or something like that ?


"better" is also a matter of opinion. It also probably depends on the
quality of implementation for your system (which is determined by both
the run-time library and the operating system).

In a system with a "good" malloc, individual calls for each node may
be preferable (less code to write, easier to maintain, etc). In a
system with a "poor" malloc, a single call for a large area which you
subdivide yourself may be preferable (program will run noticeably
faster, less fragmentation of memory, etc).
<<Remove the del for email>>
Nov 14 '05 #2
jo************* ***@hotmail.com (Joris Adriaenssens) writes:
I understand from other postings that casting a result from malloc
isn't good. In the past I have always been casting the malloc. I
think it was even necessary. (But that's a long time ago, I hadn't
heard of a standard for C these days). Was it really necessary or did
we do it only to silence the warnings ? (cfr. FAQ q7.7 - I can't
look in the manuals from these days : I don't have them any longer)
It was necessary with pre-ANSI compilers. Casting the result of
malloc() is not necessary with any ANSI C89 or later compliant
compiler. However, you'll normally get a warning if you forget
to #include <stdlib.h>. In that case, the correct fix is to add
the #include, not to add a cast.
When I use malloc for the allocation of a small piece of memory, e.g.
a single node of a linked list, I use 'free' to release the memory
afterwards. When using 'free', I don't have to worry about the size
of the allocated block the pointer is pointing to.
Is it the operating-system that is responsible to remember the size of
that piece of memory ?
Somebody has to (more or less). It may be a library linked into
your program or it may be the operating system.
In that case, when I build a large linked-list by allocating memory
for each node, I get a lot of overhead in the operating system. Is
this right ? or is this implementation-specific or operating-system
specific ?
Yes, both.
(FAQ q7.26 says that the implementation 'remembers' the size.
Does this mean that every implementation may do it in his own
way ? )
Yes.
If the computer has to remember for each single allocation the
size of the allocated block, is it better than, to allocate a
bigger piece of memory and keep track of the use of it within
the program, when I try to create a linked-list or a binary
tree or something like that ?


If you think you can do the tracking with lower overhead than the
implementation, that can be a perfectly good idea.
--
"C has its problems, but a language designed from scratch would have some too,
and we know C's problems."
--Bjarne Stroustrup
Nov 14 '05 #3

"Joris Adriaenssens" <jo************ ****@hotmail.co m> wrote

I understand from other postings that casting a result from malloc
isn't good. In the past I have always been casting the malloc. I
think it was even necessary. (But that's a long time ago, I hadn't
heard of a standard for C these days). Was it really necessary or did
we do it only to silence the warnings ? (cfr. FAQ q7.7 - I can't
look in the manuals from these days : I don't have them any longer)
C implicitly casts a void * to another type of pointer. C++ does not. The
main reason for casting the return from malloc() is to allow the code to
compile under C++. This may be necessary or even undesireable, depending on
the environment in which you work. .
Is it the operating-system that is responsible to remember the size of
that piece of memory ?
The operating system just has to allocate and free memory on demand. In
practise it usually does this by storing the size of the block in the memory
immediately before the pointer returned from malloc(). However a weird and
wonderful system may do things differently.
If the computer has to remember for each single allocation the size of
the allocated block, is it better than, to allocate a bigger piece of
memory and keep track of the use of it within the program, when I try
to create a linked-list or a binary tree or something like that ?

The best rule is to use malloc() to allocate your nodes. Then if the program
runs too slowly, you can see if you can optimise. A fixed-block allocator
can be written much more efficiently than one that has to deal with any
size. Unfortunatley the meory it uses cannot normally be recycled for
general use, so it is not a panacea.
Nov 14 '05 #4
On Mon, 6 Sep 2004 19:22:56 +0100, "Malcolm"
<ma*****@55bank .freeserve.co.u k> wrote in comp.lang.c:

"Joris Adriaenssens" <jo************ ****@hotmail.co m> wrote

I understand from other postings that casting a result from malloc
isn't good. In the past I have always been casting the malloc. I
think it was even necessary. (But that's a long time ago, I hadn't
heard of a standard for C these days). Was it really necessary or did
we do it only to silence the warnings ? (cfr. FAQ q7.7 - I can't
look in the manuals from these days : I don't have them any longer)

C implicitly casts a void * to another type of pointer. C++ does not. The

^^^^^^^^^^^^^^^ ^

No, it doesn't. C automatically converts a pointer to void to any
type of object pointer. There is no such thing as an "implicit cast"
in C, as a cast is defined as an "explicit conversion".

And there is no conversion from pointer to void to pointer to any type
of function. Only to pointer to other object types.

--
Jack Klein
Home: http://JK-Technology.Com
FAQs for
comp.lang.c http://www.eskimo.com/~scs/C-faq/top.html
comp.lang.c++ http://www.parashift.com/c++-faq-lite/
alt.comp.lang.l earn.c-c++
http://www.contrib.andrew.cmu.edu/~a...FAQ-acllc.html
Nov 14 '05 #5


Jack Klein wrote:
On Mon, 6 Sep 2004 19:22:56 +0100, "Malcolm"
<ma*****@55bank .freeserve.co.u k> wrote in comp.lang.c:

"Joris Adriaenssens" <jo************ ****@hotmail.co m> wrote
I understand from other postings that casting a result from malloc
isn't good. In the past I have always been casting the malloc. I
think it was even necessary. (But that's a long time ago, I hadn't
heard of a standard for C these days). Was it really necessary or did
we do it only to silence the warnings ? (cfr. FAQ q7.7 - I can't
look in the manuals from these days : I don't have them any longer)

C implicitly casts a void * to another type of pointer. C++ does not. The


^^^^^^^^^^^^^^^ ^

No, it doesn't. C automatically converts a pointer to void to any

^^^^^^^^^^^^^^^ ^^^^^^^ type of object pointer. There is no such thing as an "implicit cast"
in C, as a cast is defined as an "explicit conversion". ^^^^^^^^^^^^^^^ ^^^^
And there is no conversion from pointer to void to pointer to any type
of function. Only to pointer to other object types.


I don't understand this. As I read it, you are saying that C performs
an "automatic conversion" of the void *, but does not do an "explicit
conversion" (see underlined sections, above).

I understand that you are talking strictly about a cast operation; but
it seems to me that the compiler must *explicitly* convert the "void *"
to a "struct foo *" (for example).

What is the difference? Most important, what is the difference to the
*programmer* ?

--
Ron Collins
Raytheon Air Defense/RTSC/BCS

Nov 14 '05 #6
RCollins <rc***@nospam.t heriver.com> writes:
I don't understand this. As I read it, you are saying that C performs
an "automatic conversion" of the void *, but does not do an "explicit
conversion" (see underlined sections, above).

I understand that you are talking strictly about a cast operation; but
it seems to me that the compiler must *explicitly* convert the "void *"
to a "struct foo *" (for example).

What is the difference? Most important, what is the difference to the
*programmer* ?


An explicit conversion is one that you explicitly tell the
implementation to do, i.e. a cast. An automatic or implicit
conversion is done by the implementation without an explicit
request. The implementation has to do the same work regardless
of whether a conversion is implicit or explicit. The difference
is in the syntax, not the semantics.
--
"Debugging is twice as hard as writing the code in the first place.
Therefore, if you write the code as cleverly as possible, you are,
by definition, not smart enough to debug it."
--Brian Kernighan
Nov 14 '05 #7
On 7 Sep 2004 01:03:15 GMT, RCollins <rc***@nospam.t heriver.com> wrote
in comp.lang.c:


Jack Klein wrote:
On Mon, 6 Sep 2004 19:22:56 +0100, "Malcolm"
<ma*****@55bank .freeserve.co.u k> wrote in comp.lang.c:

"Joris Adriaenssens" <jo************ ****@hotmail.co m> wrote

I understand from other postings that casting a result from malloc
isn't good. In the past I have always been casting the malloc. I
think it was even necessary. (But that's a long time ago, I hadn't
heard of a standard for C these days). Was it really necessary or did
we do it only to silence the warnings ? (cfr. FAQ q7.7 - I can't
look in the manuals from these days : I don't have them any longer)
C implicitly casts a void * to another type of pointer. C++ does not. The


^^^^^^^^^^^^^^^ ^

No, it doesn't. C automatically converts a pointer to void to any

^^^^^^^^^^^^^^^ ^^^^^^^
type of object pointer. There is no such thing as an "implicit cast"
in C, as a cast is defined as an "explicit conversion".

^^^^^^^^^^^^^^^ ^^^^

And there is no conversion from pointer to void to pointer to any type
of function. Only to pointer to other object types.


I don't understand this. As I read it, you are saying that C performs
an "automatic conversion" of the void *, but does not do an "explicit
conversion" (see underlined sections, above).

I understand that you are talking strictly about a cast operation; but
it seems to me that the compiler must *explicitly* convert the "void *"
to a "struct foo *" (for example).

What is the difference? Most important, what is the difference to the
*programmer* ?


From dictionary.com, the first entry for each respective word:

implicit: Implied or understood though not directly expressed.

explicit: Fully and clearly expressed; leaving nothing implied.

Now let's look at an implicit conversion in C:

int i;
char ch = 'a';
i = ch; /* implicit conversion of char to int */

And an explicit conversion:

int i;
char ch = 'a';
i = (int)ch;

See how the first is "implied or understood but not directly
expressed" and the second is "fully and clearly expressed; leaving
nothing implied"?

The use of a cast operator is an explicit directive to the compiler to
perform a conversion. In some cases, as in the two little examples
above, the cast specifies a conversion that would be implicit anyway.
In that case, it is just what I call a "redundant cast", which is
usually but not always just useless noise.

Consider another case, assume <limits.h> is included:

int i;
double d = (double)INT_MAX + 10.0;
i = d; /* implicit automatic conversion */
i = (int)d; /* explicit "redundant" cast */

In the second example, the redundant cast gains you absolutely
nothing. d contains a value outside the range of an unsigned int, so
the implicit conversion caused by the assignment produces undefined
behavior. The explicit cast causes exactly the same undefined
behavior, so it buys nothing at all.

There are some cases where you must use a cast to cause an explicit
conversion because there is no automatic conversion, for example
between any two types of object pointers if neither is a pointer to
void:

int i = 12;
int *ip = &i; /* extra variable for documentation */
char *cp = ip; /* diagnostic required */
char *cp = (char *)ip; /* OK */

And there are some conversions that are not allowed even with a cast:

struct s1 { int i1; double d2; };
struct s2 { double d2; int i2; };

struct s1 { 3, 42.0 };
struct s2;
s2 = s1;
s2 = (struct st)si;

And as for my assertion that a cast is an explicit conversion, rather
than an automatic conversion being a implicit cast, that comes from
the wording of the C standard itself:

6.3 Conversions

1 Several operators convert operand values from one type to another
automatically. This subclause specifies the result required from such
an implicit conversion, as well as those that result from a cast
operation (an explicit conversion). The list in 6.3.1.8 summarizes
the conversions performed by most ordinary operators; it is
supplemented as required by the discussion of each operator in 6.5.

--
Jack Klein
Home: http://JK-Technology.Com
FAQs for
comp.lang.c http://www.eskimo.com/~scs/C-faq/top.html
comp.lang.c++ http://www.parashift.com/c++-faq-lite/
alt.comp.lang.l earn.c-c++
http://www.contrib.andrew.cmu.edu/~a...FAQ-acllc.html
Nov 14 '05 #8
Ben Pfaff <bl*@cs.stanfor d.edu> wrote in message news:<87******* *****@benpfaff. org>...
I understand from other postings that casting a result from malloc
isn't good. In the past I have always been casting the malloc. I
think it was even necessary. (But that's a long time ago, I hadn't
heard of a standard for C these days). Was it really necessary or did
we do it only to silence the warnings ? (cfr. FAQ q7.7 - I can't
look in the manuals from these days : I don't have them any longer)
It was necessary with pre-ANSI compilers. Casting the result of
malloc() is not necessary with any ANSI C89 or later compliant
compiler. However, you'll normally get a warning if you forget
to #include <stdlib.h>. In that case, the correct fix is to add
the #include, not to add a cast.


....

Thanks for the fast replies. They are very clear to me.
Nov 14 '05 #9
Joris Adriaenssens wrote:
[...]
I understand from other postings that casting a result from malloc
isn't good. In the past I have always been casting the malloc. I
think it was even necessary. (But that's a long time ago, I hadn't
heard of a standard for C these days). Was it really necessary or did
we do it only to silence the warnings ? (cfr. FAQ q7.7 - I can't
look in the manuals from these days : I don't have them any longer)

[...]

It was necessary back in the days when malloc() returned char* because
there was no such thing as "void" yet.

Now that malloc() returns void*, which can be implicitly converted to
anything*, it is considered "bad" to cast the return value, as this can
mask a missing header file. (ie: if malloc() isn't defined in any of
the header files, the compiler will think it returns int, and the cast
will mask the warning about converting int to a pointer.)

--
+-------------------------+--------------------+-----------------------------+
| Kenneth J. Brody | www.hvcomputer.com | |
| kenbrody/at\spamcop.net | www.fptech.com | #include <std_disclaimer .h> |
+-------------------------+--------------------+-----------------------------+
Nov 14 '05 #10

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

Similar topics

9
4024
by: WL | last post by:
Hey, all. I'm creating an array of strings (char **argv style) on the fly, and using realloc to create string pointers, and malloc for the strings itself (if that makes any sense). I'm using the construct ptr = realloc(ptr, size); *ptr = malloc(string_length); strncpy(ptr, src, string_length); to call realloc() multiple times. This should be ok, right?
13
815
by: Steve Zimmerman | last post by:
Esteemed contributors to clc: Thank you for all the responses. Experiments 2 and 3 below are identical, except that experiment 2 does not call free(), while experiment 3 does. With such a trivial program, is it safe not to call free()? Are there dangers in experiment 2 that experiment 3 avoids?
21
34374
by: kent lavallie | last post by:
Hi. I am an amature c hobbyist and I wish to begin using malloc as I have been told that running executables from executables is a less than elegant way to manage memory use. I need basic examples so me and my compiler can get familliar with malloc. Please give examples that do not contain nested assignments and the like as I will get lost quite easily. As an example of my rudimentary style take a look at how I create an array and assign a...
34
6427
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. --
27
4260
by: Chess Saurus | last post by:
I'm getting a little bit tired of writing if (a = malloc(...) == NULL) { // error code } I mean, is it really possible that a malloc call could fail, except in the case of running out of virtual memory? -Chess
7
2206
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...
18
3306
by: cs | last post by:
This is the function malloc_m() that should be like malloc() but it should find memory leak, and over bound writing in arrays. How many errors do you see? Thank you ******************************************** /* mallocm.c */ /* funzione di libreria per trattamento della memoria e rilevamento errori */ /* uso: c_compiler malloc.c e usare malloc .obj */
15
2576
by: Martin Jørgensen | last post by:
Hi, I have a (bigger) program with about 15-30 malloc's in it (too big to post it here)... The last thing I tried today was to add yet another malloc **two_dimensional_data. But I found out that malloc always returned null at this moment and the program exited (even though if I malloc'ed only 20 bytes or something)... Then I googled for this problem and found something about a memory pool??? Is that standard C? I didn't understand it,...
3
3618
by: Petr Pavlu | last post by:
Hello, I have two questions how the functions should be written. I read the FAQ but didn't find any answer. If there is any please point me out. I. Cleanup code Consider I have to open file1, then make some malloc and then open file2. What is the best solution how to write the cleanup code? See my pseudo- code ideas.
25
3367
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,...
0
8425
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8845
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...
1
8522
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
7355
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...
0
5647
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4173
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
4333
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2745
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1736
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.