By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
449,310 Members | 1,944 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 449,310 IT Pros & Developers. It's quick & easy.

How does free() knows?

P: n/a
I wish to know how the free()function knows how much memory to be
freed as we only give pointer to allocated memory as an argument to
free(). Does system use an internal variable to store allocated memory
when we use malloc().
Plz help......
Nov 14 '05 #1
Share this Question
Share on Google+
74 Replies


P: n/a
Suyog_Linux <su******@yahoo.com> scribbled the following
on comp.lang.c:
I wish to know how the free()function knows how much memory to be
freed as we only give pointer to allocated memory as an argument to
free(). Does system use an internal variable to store allocated memory
when we use malloc().
Plz help......


It depends entirely on the implementation. An internal variable is one
way, but there might be others. The standard does not mandate any
specific way.

--
/-- Joona Palaste (pa*****@cc.helsinki.fi) ------------- Finland --------\
\-- http://www.helsinki.fi/~palaste --------------------- rules! --------/
"The question of copying music from the Internet is like a two-barreled sword."
- Finnish rap artist Ezkimo
Nov 14 '05 #2

P: n/a
"Suyog_Linux" <su******@yahoo.com> wrote in message
news:df**************************@posting.google.c om...
I wish to know how the free()function knows how much memory to be
freed as we only give pointer to allocated memory as an argument to
free(). Does system use an internal variable to store allocated memory
when we use malloc().


Most likely yes, although there is no portable way for users' programs to
get at this value.

I guess it's also possible that it might not keep the length explicity but
might instead keep a pointer to the next block, or maybe just keeps lists of
blocks of various sizes and get malloc to hand out a block from the list
with the next larger block... Or other schemes.

Given that the system almost certainly knows how big the block is I'm always
a little suprised that there is not getallocsize(void*) or some such
function to get the amount of allocated space in a block as it would be
fairly useful for some applications.
Nov 14 '05 #3

P: n/a
su******@yahoo.com (Suyog_Linux) wrote:
# I wish to know how the free()function knows how much memory to be
# freed as we only give pointer to allocated memory as an argument to
# free(). Does system use an internal variable to store allocated memory
# when we use malloc().

The implementation is permitted any magic that correctly implements the interface.

With terabytes of VM and 64 bit addresses becoming available, an acceptable malloc
implementation for many programs is that malloc always allocates new memory
and free doesn't do anything but immediately return. Such an implementation doesn't
need to store block sizes anywhere.

--
SM Ryan http://www.rawbw.com/~wyrmwif/
Who's leading this mob?
Nov 14 '05 #4

P: n/a

"Joona I Palaste" <pa*****@cc.helsinki.fi> wrote in message
news:ch**********@oravannahka.helsinki.fi...
Suyog_Linux <su******@yahoo.com> scribbled the following
on comp.lang.c:
I wish to know how the free()function knows how much memory to be freed as we only give pointer to allocated memory as an argument to free(). Does system use an internal variable to store allocated memory when we use malloc().
Plz help......
It depends entirely on the implementation. An internal variable

is one way, but there might be others. The standard does not mandate any specific way.

Out of curiosity (and I know that the standard does not mandate
any specific way) but are the mechancis of this something that is
usually handled by the program code (the stuff thrown in by the
compiler) or are the mechanics generally done by the operating
system? Which side of the house, more often than not, keeps track
of this? Would it be reasonable (not necessarily right and
certainly not guaranteed to be right) to suspect that with
smaller code sizes (memory models) that the program's "heap"
space is a block of memory that the OS gave it as start up and
the program manages the assignment requests within that block but
if you are working with a program that can request, at least
cumulatively, hundreds of megabytes of dynamic memory that the
program requests additional memory from the OS (perhaps in fewer,
but larger chunks) and the OS keeps track of the butcher's bill
for that?
--
/-- Joona Palaste (pa*****@cc.helsinki.fi) ------------- Finland --------\ \-- http://www.helsinki.fi/~palaste --------------------- rules! --------/ "The question of copying music from the Internet is like a two-barreled sword." - Finnish rap artist Ezkimo

Nov 14 '05 #5

P: n/a
SM Ryan wrote:
su******@yahoo.com (Suyog_Linux) wrote:
# I wish to know how the free()function knows how much memory to be
# freed as we only give pointer to allocated memory as an argument to
# free(). Does system use an internal variable to store allocated memory
# when we use malloc().

The implementation is permitted any magic that correctly implements the interface.

With terabytes of VM and 64 bit addresses becoming available, an acceptable malloc
implementation for many programs is that malloc always allocates new memory
and free doesn't do anything but immediately return. Such an implementation doesn't
need to store block sizes anywhere.


That would be a memory leak. At least free needs to flag something,
so that memory manager may act in the b.g. to get the job done.
--
Karthik.
Nov 14 '05 #6

P: n/a

"Suyog_Linux" <su******@yahoo.com> wrote in message
news:df**************************@posting.google.c om...
I wish to know how the free()function knows how much memory to be
freed as we only give pointer to allocated memory as an argument to
free(). Does system use an internal variable to store allocated memory
when we use malloc().
Plz help......


One sneaky method is to hide that sort of information before the pointer
address returned by malloc(). So free() takes the address, then goes a few
addresses back, and knows the information on the size of the memory that was
allocated.

As stated in other offshoots of this post, there is no standard method to do
this prescribed by the standard.

Michael Steve
Nov 14 '05 #7

P: n/a

"Suyog_Linux" <su******@yahoo.com> wrote in message
news:df**************************@posting.google.c om...
I wish to know how the free()function knows how much memory to be
freed as we only give pointer to allocated memory as an argument to
free(). Does system use an internal variable to store allocated memory
when we use malloc().
Plz help......


See Knuth's works for descriptions on memory allocation techniques. Of
course there might be an infinite number of different ways of implementing
memory allocation, but at least he describes some of them.
Nov 14 '05 #8

P: n/a

"Suyog_Linux" <su******@yahoo.com> skrev i en meddelelse
news:df**************************@posting.google.c om...
I wish to know how the free()function knows how much memory to be
freed as we only give pointer to allocated memory as an argument to
free(). Does system use an internal variable to store allocated memory
when we use malloc().
Plz help......


There is no standard way. Also bear in mind that "how much memory to be
freed" might not be the same as "how much memory was allocated".

/Peter
Nov 14 '05 #9

P: n/a
In article <41**********************@news.aaisp.net.uk>,
John Burton <jo*********@jbmail.com> wrote:
I guess it's also possible that it might not keep the length explicity


One way is to allocate blocks of different sizes from different areas
of memory, so that the size is implicit in the high-order address
bits. This technique is also used for object typing in
implementations of some languages, where it's known as "bibop".

-- Richard
Nov 14 '05 #10

P: n/a
William L. Bahn wrote:
"Joona I Palaste" <pa*****@cc.helsinki.fi> wrote in message
news:ch**********@oravannahka.helsinki.fi...
Suyog_Linux <su******@yahoo.com> scribbled the following
on comp.lang.c:
I wish to know how the free()function knows how much memory
to be
freed as we only give pointer to allocated memory as an
argument to
free(). Does system use an internal variable to store
allocated memory
when we use malloc().
Plz help......
It depends entirely on the implementation. An internal variable


is one
way, but there might be others. The standard does not mandate


any
specific way.

Out of curiosity (and I know that the standard does not mandate
any specific way) but are the mechancis of this something that is
usually handled by the program code (the stuff thrown in by the
compiler) or are the mechanics generally done by the operating
system?

The mechanics are up to the compiler implementor. Some compilers
have their own memory allocation schemes. Others use the operating
systems memory management routines. Still other compilers allow
users to provide their own.

There is nothing stopping program code from implementing
its own memory management.

Which side of the house, more often than not, keeps track
of this? Probably the dark side; could be the section between the
ceiling and the bottom of the upper floor (where the pipes
may live).

Most programs leave memory management up to the compiler
implementation. Some non-portable programs may use the
operating system features. And yet other programs implement
their own memory management scheme. The simplest method
is to use the language memory allocation features and don't
worry _how_ it is implemented. There are more important
topics to worry about, such as program correctness, than
what operates under the hood of a language.

Would it be reasonable (not necessarily right and
certainly not guaranteed to be right) to suspect that with
smaller code sizes (memory models) that the program's "heap"
space is a block of memory that the OS gave it as start up and
the program manages the assignment requests within that block but
if you are working with a program that can request, at least
cumulatively, hundreds of megabytes of dynamic memory that the
program requests additional memory from the OS (perhaps in fewer,
but larger chunks) and the OS keeps track of the butcher's bill
for that?

Could be reasonable, could not be. Depends.
Many multi-user systems have different memory sizes set aside
for different users. Some operating systems implement a paging
system, where the program is given a "page" of memory and any
allocation beyond that page cause another one to be loaded in.
Some systems have a fixed memory size regardless of the executable
code size.

Executable code size has no relationship to the amount of memory
required by the executable program. A small program can be written
that uses a lot of memory while a large program can be written
that uses very little memory.

Focus on completing the program and getting all the bugs out
(correctness) before even thinking about how much memory it
needs, how fast it is or the size of the code. The latter
topics can all be optimized after profiling the program.
--
Thomas Matthews

C++ newsgroup welcome message:
http://www.slack.net/~shiva/welcome.txt
C++ Faq: http://www.parashift.com/c++-faq-lite
C Faq: http://www.eskimo.com/~scs/c-faq/top.html
alt.comp.lang.learn.c-c++ faq:
http://www.comeaucomputing.com/learn/faq/
Other sites:
http://www.josuttis.com -- C++ STL Library book

Nov 14 '05 #11

P: n/a
Suyog_Linux wrote:
I wish to know how the free()function knows how much memory to be
freed as we only give pointer to allocated memory as an argument to
free(). Does system use an internal variable to store allocated memory
when we use malloc().
Plz help......


Another method is to supply the size of the target in
the pointer structure:
<address, block size>
{Hey, I said it was another idea, maybe not the best.}
--
Thomas Matthews

C++ newsgroup welcome message:
http://www.slack.net/~shiva/welcome.txt
C++ Faq: http://www.parashift.com/c++-faq-lite
C Faq: http://www.eskimo.com/~scs/c-faq/top.html
alt.comp.lang.learn.c-c++ faq:
http://www.comeaucomputing.com/learn/faq/
Other sites:
http://www.josuttis.com -- C++ STL Library book

Nov 14 '05 #12

P: n/a
Suyog_Linux wrote:
I wish to know how the free()function knows how much memory to be
freed as we only give pointer to allocated memory as an argument to
free().


A very common way of doing this is to store the size in a word
immediately before the allocated block in memory. This is so common in
fact that it has led to a general assumption that allocating lots of
small objects is bad, and pools should be constructed instead, to
prevent internal fragmentation. An allocator that dealt with small
objects in an intelligent way would eliminate such silly optimizations.
--
Derrick Coetzee
I grant this newsgroup posting into the public domain. I disclaim all
express or implied warranty and all liability. I am not a professional.
Nov 14 '05 #13

P: n/a
http://www.cours.polymtl.ca/inf6100/...ap9/chap9.html
The above link shows you how this works. Unfortunatly, it is written in French.

Peter
www.1sttechnews.com
"John Smith" <so*****@microsoft.com> wrote in message news:<ch**********@newstree.wise.edt.ericsson.se>. ..
"Suyog_Linux" <su******@yahoo.com> wrote in message
news:df**************************@posting.google.c om...
I wish to know how the free()function knows how much memory to be
freed as we only give pointer to allocated memory as an argument to
free(). Does system use an internal variable to store allocated memory
when we use malloc().
Plz help......


See Knuth's works for descriptions on memory allocation techniques. Of
course there might be an infinite number of different ways of implementing
memory allocation, but at least he describes some of them.

Nov 14 '05 #14

P: n/a
Thomas Matthews wrote:
.... snip ...
Executable code size has no relationship to the amount of memory
required by the executable program. A small program can be written
that uses a lot of memory while a large program can be written
that uses very little memory.


This has (and has had) nothing to do with c.l.c++. F'ups set.

The following baby program will show how much memory you can
allocate in your system to a single object. If the returned
pointers change for each iteration the malloc package probably
does not go to any effort to avoid unnecessary copying, and maybe
needlessly slow.

/* mgobble.c - gobble as much memory as possible */

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
char *temp, *gobbler = NULL;
size_t sz = 1;

while ((temp = realloc(gobbler, sz))) {
printf("%10lu %p\n", (unsigned long)sz, (void *)temp);
gobbler = temp;
sz += sz;
}
free(gobbler);
return 0;
} /* main mgobble.c */

--
A: Because it fouls the order in which people normally read text.
Q: Why is top-posting such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Nov 14 '05 #15

P: n/a
Thomas Matthews <Th****************************@sbcglobal.net> writes:
William L. Bahn wrote: [...]
Out of curiosity (and I know that the standard does not mandate
any specific way) but are the mechancis of this something that is
usually handled by the program code (the stuff thrown in by the
compiler) or are the mechanics generally done by the operating
system?

The mechanics are up to the compiler implementor. Some compilers
have their own memory allocation schemes. Others use the operating
systems memory management routines. Still other compilers allow
users to provide their own.


To be precise, it's up to the runtime library implementor. We often
use the term "compiler" to refer to the entire C implementation, but
it's more correct to refer to the compiler and the standard library as
separate things. They typically aren't even implemented by the same
people.

For example, on a Solaris system, I might gcc, but if my program
contains a call to malloc() or free(), the compiler just generates a
function call. The actual implementation is part of the runtime
library provided by Sun.
There is nothing stopping program code from implementing
its own memory management.


True, but you're likely to run into problems if you try to use the
names "malloc" and "free" for your memory management. (Some systems
may have ways of overriding the system memory management functions;
the details are off-topic here.) If you want to write your own
my_malloc() and my_free() functions, of course you can do so -- but
then system routines that your program calls are likely to use the
predefined malloc() and free(), so your memory manager had better be
able to coexist with the one provided by the system.

--
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 14 '05 #16

P: n/a
ri*****@cogsci.ed.ac.uk (Richard Tobin) writes:
In article <41**********************@news.aaisp.net.uk>,
John Burton <jo*********@jbmail.com> wrote:
I guess it's also possible that it might not keep the length explicity


One way is to allocate blocks of different sizes from different areas
of memory, so that the size is implicit in the high-order address
bits. This technique is also used for object typing in
implementations of some languages, where it's known as "bibop".


Really? That sounds like it could be terribly inefficient -- a
program that allocates only chunks of a certain size could run out of
memory when there's still plenty left in another region. Though I
suppose the implementation could do something fancy in mapping real to
virtual addresses, so the unused areas don't actually exist.

I found a web reference to something called "Big Bag of Pages",
abbreviated "bipop". But I'm a bit skeptical that this would make
sense for a C-style malloc/free system.

Nevertheless, it's a good example of the kind of thing the standard
allows -- which means programmers who make unwarranted assumptions
about the inner workings of the memory management system are likely to
get into trouble.

--
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 14 '05 #17

P: n/a
Thomas Matthews <Th****************************@sbcglobal.net> writes:
Suyog_Linux wrote:
I wish to know how the free()function knows how much memory to be
freed as we only give pointer to allocated memory as an argument to
free(). Does system use an internal variable to store allocated memory
when we use malloc().
Plz help......


Another method is to supply the size of the target in
the pointer structure:
<address, block size>
{Hey, I said it was another idea, maybe not the best.}


You'd need an offset along with the base address and size. For
example, the following is valid:

char *p = malloc(100);
char *q = p + 10;
free(q - 10);

If the information needed by free() is going to be stored in the
pointer, then q has to retain enough information to get back to the
base address of the allocated object. Either the "address" field of q
points to the base of the allocated object, with an offset of 10, or
the "address" field points directly to p[10] and the offset is -10;
the latter scheme might make for more efficient code.

This also gives you the possibility of run-time bounds checking.

--
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 14 '05 #18

P: n/a
SM Ryan <wy*****@tango-sierra-oscar-foxtrot-tango.fake.org> writes:
su******@yahoo.com (Suyog_Linux) wrote:
# I wish to know how the free()function knows how much memory to be
# freed as we only give pointer to allocated memory as an argument to
# free(). Does system use an internal variable to store allocated memory
# when we use malloc().

The implementation is permitted any magic that correctly implements
the interface.

With terabytes of VM and 64 bit addresses becoming available, an
acceptable malloc implementation for many programs is that malloc
always allocates new memory and free doesn't do anything but
immediately return. Such an implementation doesn't need to store
block sizes anywhere.


Please use the conventional "> " prefix for quoted text.
Please keep your lines down to about 72 columns.
Please use the standard "-- " signature delimiter.

I don't believe that an implementation of free() that does nothing
would be acceptable. The "terabytes of VM" you're talking about are
typically stored on disk; if you allocate more than the amount of
physical memory, your program is going to slow down as it swaps data
between disk and memory. For that matter, you're likely to slow down
the entire system, and you'll still run out eventually.

I work on some pretty big systems; they typically have no more than a
few gigabytes of virtual memory.

Even assuming terabytes of fast, cheap virtual memory and a full
64-bit address space, consider a program that does something like
this:

while (1) {
/* allocate a few megabytes of memory */
/* do some work */
/* free the allocated memory */
}

(Think of a server or a system daemon that runs continuously for
months at a time.) If free() does nothing, this is a serious memory
leak which will crash the program and/or bog down the system.

Fortunately, I don't believe that anyone has actually implemented such
a system.

--
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 14 '05 #19

P: n/a
Suyog_Linux wrote:
I wish to know how the free()function knows
how much memory to be freed
as we only give pointer to allocated memory as an argument to free().
Does system use an internal variable to store allocated memory
when we use malloc().
It depends upon the implementation.
Try this:
cat main.c #include <stdio.h>
#include <stdlib.h>

int main(int argc, char* argv[]) {
if (1 < argc) {
const
size_t n = atoi(argv[1]);
int* p = (int*)malloc(n*sizeof(int));
fprintf(stdout, "%d = p[-1]\n", p[-1]);
}
return 0;
}
gcc -Wall -std=c99 -pedantic -o main main.c
./main 1 17 = p[-1] ./main 2 17 = p[-1] ./main 3 17 = p[-1] ./main 4 25 = p[-1] ./main 5 25 = p[-1] ./main 6 33 = p[-1] ./main 7 33 = p[-1] ./main 8 41 = p[-1] ./main 9 41 = p[-1] gcc --version

gcc (GCC) 3.3.3 20040412 (Red Hat Linux 3.3.3-7)
Nov 14 '05 #20

P: n/a
In article <ln************@nuthaus.mib.org>,
Keith Thompson <ks***@mib.org> wrote:
Really? That sounds like it could be terribly inefficient -- a
program that allocates only chunks of a certain size could run out of
memory when there's still plenty left in another region. Though I
suppose the implementation could do something fancy in mapping real to
virtual addresses, so the unused areas don't actually exist.
Yes, you would probably map the regions as required on a modern machine.

Even without that, the pages for a given size don't all have to be
contiguous. You can have a map from high-order bits to sizes, and a
list of regions for going the other way.
I found a web reference to something called "Big Bag of Pages",
abbreviated "bipop".


That's it.

-- Richard
Nov 14 '05 #21

P: n/a
>> Another method is to supply the size of the target in
the pointer structure:
<address, block size>
{Hey, I said it was another idea, maybe not the best.}
You'd need an offset along with the base address and size. For


Why? Not for just carrying the block size in the pointer.
example, the following is valid:

char *p = malloc(100);
char *q = p + 10;
free(q - 10);

If the information needed by free() is going to be stored in the
pointer, then q has to retain enough information to get back to the
base address of the allocated object.
If incrementing p modifies only the address, and leaves alone the
block size, and decrementing q modifies only the address, and leaves
alone the block size, then the above will still work, without needing
an offset.

Passing q (not q - 10) directly to free() invokes undefined behavior,
and the fact that q contains a block size that is not accurate for
the address in q doesn't make the problem any worse. It's already
as bad as it gets.
Either the "address" field of q
points to the base of the allocated object, with an offset of 10, or
the "address" field points directly to p[10] and the offset is -10;
the latter scheme might make for more efficient code.
You don't need an offset field.
This also gives you the possibility of run-time bounds checking.


Run-time bounds checking does require the offset field, but it
isn't a requirement for passing the block size in the pointer.

Gordon L. Burditt
Nov 14 '05 #22

P: n/a
su******@yahoo.com (Suyog_Linux) wrote in message news:<df**************************@posting.google. com>...
I wish to know how the free()function knows how much memory to be
freed as we only give pointer to allocated memory as an argument to
free(). Does system use an internal variable to store allocated memory
when we use malloc().
Plz help......


Most standard allocators do not keep track of the size! They just
keep an ordered alloc/free list. The point is to make the allocator
fast.

The downside of this strategy is that free is totally error prone.
Free'ing the same block twice will corrupt the heap, free'ing a stack
value or global value will corrupt the heap, free'ing a misaligned ptr
will corrupt the heap, etc, etc.

My company, Dynamic Memory Solutions, markets Dynamic Leak Check that
checks for these sorts of errors, www.dynamic-memory.com. Dynamic Leak
Check has a custom allocator that catches error but is significantly
than the standard allocator.

Matthew
Dynamic Memory Solutions
www.dynamic-memory.com
Nov 14 '05 #23

P: n/a
Apologies for going OT, but, well, maybe you'll understand...

CBFalconer wrote:
Thomas Matthews wrote:

... snip ...

Executable code size has no relationship to the amount of memory
required by the executable program. A small program can be written
that uses a lot of memory while a large program can be written
that uses very little memory.


This has (and has had) nothing to do with c.l.c++. F'ups set.

The following baby program will show how much memory you can
allocate in your system to a single object. If the returned
pointers change for each iteration the malloc package probably
does not go to any effort to avoid unnecessary copying, and maybe
needlessly slow.

/* mgobble.c - gobble as much memory as possible */

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
char *temp, *gobbler = NULL;
size_t sz = 1;

while ((temp = realloc(gobbler, sz))) {
printf("%10lu %p\n", (unsigned long)sz, (void *)temp);
gobbler = temp;
sz += sz;
}
free(gobbler);
return 0;
} /* main mgobble.c */

Hmm. I tried this on Slackware 10,
$ gcc -dumpversion
3.3.4

but modified it a little, to see if I could "see" what's happening:
/* mgobble.c - gobble as much memory as possible */
/* mod Rich 2 */
#include <stdio.h>
#include <stdlib.h>

char myinput[512];

int main(void)
{
char *temp, *gobbler = NULL;
size_t sz = 1;

while ((temp = realloc(gobbler, sz))) {
printf("%10lu %p\n", (unsigned long)sz, (void *)temp);
gobbler = temp;
sz += sz;
/* printf("Hit enter to continue... ");
fflush(stdout);
gets(myinput);
*/
system("free");
}
free(gobbler);
return 0;
} /* main mgobble.c */

And apparently I'm looking at the wrong thing - here's abridged
output:
rich@entheos:~/Programming/C
$ mgobble
1 0x8049910
total used free shared buffers cached
Mem: 515440 323688 191752 0 83388 119316
-/+ buffers/cache: 120984 394456
Swap: 995988 0 995988
2 0x8049910
total used free shared buffers cached
Mem: 515440 323688 191752 0 83388 119316
-/+ buffers/cache: 120984 394456
Swap: 995988 0 995988
4 0x8049910
total used free shared buffers cached
Mem: 515440 323688 191752 0 83388 119316
-/+ buffers/cache: 120984 394456
Swap: 995988 0 995988
....
268435456 0x4015c008
total used free shared buffers cached
Mem: 515440 323800 191640 0 83388 119316
-/+ buffers/cache: 121096 394344
Swap: 995988 0 995988
536870912 0x4015c008
total used free shared buffers cached
Mem: 515440 323800 191640 0 83388 119316
-/+ buffers/cache: 121096 394344
Swap: 995988 0 995988
1073741824 0x4015c008
total used free shared buffers cached
Mem: 515440 323808 191632 0 83388 119316
-/+ buffers/cache: 121104 394336
Swap: 995988 0 995988
rich@entheos:~/Programming/C

The little program says it has allocated a gigabyte, but free tells me
that almost nothing is used. What does this mean?

Thanks,
Rich

Nov 14 '05 #24

P: n/a
E. Robert Tisdale wrote:
Suyog_Linux wrote:
I wish to know how the free()function knows how much memory to be
freed as we only give pointer to allocated memory as an argument to
free(). Does system use an internal variable to store allocated memory
when we use malloc().

It depends upon the implementation.
Try this:

What does this show?

> cat main.c

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char* argv[]) {
if (1 < argc) {
const
size_t n = atoi(argv[1]);
int* p = (int*)malloc(n*sizeof(int));


Why, OH WHY, would you cast malloc?????
And what does malloc(0) return?
fprintf(stdout, "%d = p[-1]\n", p[-1]);
}
return 0;
}
> gcc -Wall -std=c99 -pedantic -o main main.c


[snip]

Nov 14 '05 #25

P: n/a
"dbtid" <db***@dev.null.us> wrote in message
news:MF********************@fe2.columbus.rr.com...
int* p = (int*)malloc(n*sizeof(int));


Why, OH WHY, would you cast malloc?????


I thought you HAD to cast malloc(). Malloc() returns a void pointer.

....am I going insane (again)?

--
Mabden
Nov 14 '05 #26

P: n/a
"Mabden" <mabden@sbc_global.net> writes:
I thought you HAD to cast malloc(). Malloc() returns a void pointer.

...am I going insane (again)?


I don't recommend casting the return value of malloc():

* The cast is not required in ANSI C.

* Casting its return value can mask a failure to #include
<stdlib.h>, which leads to undefined behavior.

* If you cast to the wrong type by accident, odd failures can
result.

Some others do disagree, such as P.J. Plauger (see article
<9s*****************@nwrddc01.gnilink.net>).

--
Ben Pfaff
email: bl*@cs.stanford.edu
web: http://benpfaff.org
Nov 14 '05 #27

P: n/a
Mabden <mabden@sbc_global.net> wrote:
"dbtid" <db***@dev.null.us> wrote in message
news:MF********************@fe2.columbus.rr.com...
> int* p = (int*)malloc(n*sizeof(int));
Why, OH WHY, would you cast malloc?????

I thought you HAD to cast malloc(). Malloc() returns a void pointer. ...am I going insane (again)?


Are you serious? See the FAQ section 7.7. If that doesn't convince
you see the errata page for K&R2 where they retract their original
recommedation to cast the return value malloc().

Regards, Jens
--
\ Jens Thoms Toerring ___ Je***********@physik.fu-berlin.de
\__________________________ http://www.toerring.de
Nov 14 '05 #28

P: n/a
Mabden wrote:
dbtid wrote:
int* p = (int*)malloc(n*sizeof(int));
Why, OH WHY, would you cast malloc?????


I thought you HAD to cast malloc().


You do in C++ but not in C.
Suyog_Linux cross posted to both comp.lang.c and comp.lang.c++
so I posted an example that both C and C++ compilers should accept.
Malloc() returns a void pointer.
...am I going insane (again)?


Probably.
Nov 14 '05 #29

P: n/a
Ben Pfaff wrote:
I don't recommend casting the return value of malloc():

* Casting its return value can mask a failure to #include
<stdlib.h>, which leads to undefined behavior.
Only if you have a lame compiler:
cat main.c #include <stdio.h>
// #include <stdlib.h>

int main(int argc, char* argv[]) {
if (1 < argc) {
const
size_t n = atoi(argv[1]);
int* p = (int*)malloc(n*sizeof(int));
fprintf(stdout, "%d = p[-1]\n", p[-1]);
}
return 0;
}
gcc -Wall -std=c99 -pedantic -o main main.c

main.c: In function `main':
main.c:7: warning: implicit declaration of function `atoi'
main.c:8: warning: implicit declaration of function `malloc'
Nov 14 '05 #30

P: n/a
go***********@burditt.org (Gordon Burditt) writes:
Another method is to supply the size of the target in
the pointer structure:
<address, block size>
{Hey, I said it was another idea, maybe not the best.}


You'd need an offset along with the base address and size. For


Why? Not for just carrying the block size in the pointer.
example, the following is valid:

char *p = malloc(100);
char *q = p + 10;
free(q - 10);

If the information needed by free() is going to be stored in the
pointer, then q has to retain enough information to get back to the
base address of the allocated object.


If incrementing p modifies only the address, and leaves alone the
block size, and decrementing q modifies only the address, and leaves
alone the block size, then the above will still work, without needing
an offset.

Passing q (not q - 10) directly to free() invokes undefined behavior,
and the fact that q contains a block size that is not accurate for
the address in q doesn't make the problem any worse. It's already
as bad as it gets.


You're right. I was thinking in terms of an error-checking free(),
which of course is not required.

The suggested approach would mean that a lot of pointers would be
carrying a meaningless block size. An implementer adding this kind of
information to pointers probably might as well add an offset as well,
so it's useful for error checking, but it's not required.

--
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 14 '05 #31

P: n/a
E. Robert Tisdale <E.**************@jpl.nasa.gov> wrote:
Ben Pfaff wrote:
I don't recommend casting the return value of malloc():

* Casting its return value can mask a failure to #include
<stdlib.h>, which leads to undefined behavior. Only if you have a lame compiler: > cat main.c

#include <stdio.h>
// #include <stdlib.h>

int main(int argc, char* argv[]) {
if (1 < argc) {
const
size_t n = atoi(argv[1]);
int* p = (int*)malloc(n*sizeof(int));
fprintf(stdout, "%d = p[-1]\n", p[-1]);
}
return 0;
}

> gcc -Wall -std=c99 -pedantic -o main main.c

main.c: In function `main':
main.c:7: warning: implicit declaration of function `atoi'
main.c:8: warning: implicit declaration of function `malloc'


What's so hard to understand about the word "can" Ben was using?
BTW, if you leave out the '-Wall' option, as many newbies will do,
also gcc won't output a warning. And "lameness" of compilers is
off-topic here, "lameness" is nowhere defined in the standard;-)

Regards, Jens
--
\ Jens Thoms Toerring ___ Je***********@physik.fu-berlin.de
\__________________________ http://www.toerring.de
Nov 14 '05 #32

P: n/a
Rich Grise wrote:

Apologies for going OT, but, well, maybe you'll understand...

CBFalconer wrote:
Thomas Matthews wrote:
... snip ...

Hmm. I tried this on Slackware 10,
$ gcc -dumpversion
3.3.4

but modified it a little, to see if I could "see" what's happening:
/* mgobble.c - gobble as much memory as possible */
/* mod Rich 2 */
#include <stdio.h>
#include <stdlib.h>

char myinput[512];

int main(void)
{
char *temp, *gobbler = NULL;
size_t sz = 1;

while ((temp = realloc(gobbler, sz))) {
printf("%10lu %p\n", (unsigned long)sz, (void *)temp);
gobbler = temp;
sz += sz;
/* printf("Hit enter to continue... ");
fflush(stdout);
gets(myinput);
*/
system("free");
}
free(gobbler);
return 0;
} /* main mgobble.c */

And apparently I'm looking at the wrong thing - here's abridged
output:
rich@entheos:~/Programming/C
$ mgobble
1 0x8049910
total used free shared buffers cached
Mem: 515440 323688 191752 0 83388 119316
-/+ buffers/cache: 120984 394456

.... snip ...
The little program says it has allocated a gigabyte, but free tells me
that almost nothing is used. What does this mean?


I have no idea. You should be asking this in a group devoted to
your system, where they may well be able to tell you.
system("free") has no established meaning in C. That is why OT
posts are purposeless.

BTW you should never, ever, use gets. getchar would have sufficed.

--
"A man who is right every time is not likely to do very much."
-- Francis Crick, co-discover of DNA
"There is nothing more amazing than stupidity in action."
-- Thomas Matthews
Nov 14 '05 #33

P: n/a
"E. Robert Tisdale" wrote:
Suyog_Linux wrote:
I wish to know how the free()function knows
how much memory to be freed
as we only give pointer to allocated memory as an argument to free().
Does system use an internal variable to store allocated memory
when we use malloc().


It depends upon the implementation.
Try this:
> cat main.c

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char* argv[]) {
if (1 < argc) {
const
size_t n = atoi(argv[1]);
int* p = (int*)malloc(n*sizeof(int));
fprintf(stdout, "%d = p[-1]\n", p[-1]);
}
return 0;
}
> gcc -Wall -std=c99 -pedantic -o main main.c
> ./main 1

17 = p[-1]

.... snip ...

Don't try this. It invokes undefined behavior and other poor
programming practices and is meaningless in portable C. In
addition Trollsdale seems to have deliberately attempted to
maximize annoyance by cross-posting to c.l.c++ where it is even
further OT.

Maybe we should save this as a horrible example to show to his
alleged superiors at JPL. We probably don't have to, google will
archive it. How many NASA shots has he destroyed so far?

--
"A man who is right every time is not likely to do very much."
-- Francis Crick, co-discover of DNA
"There is nothing more amazing than stupidity in action."
-- Thomas Matthews
Nov 14 '05 #34

P: n/a
Matthew Fisher wrote:
.... snip ...
Most standard allocators do not keep track of the size! They just
keep an ordered alloc/free list. The point is to make the allocator
fast.
Nonsense. There is no such thing as a standard allocator.

The downside of this strategy is that free is totally error prone.
Free'ing the same block twice will corrupt the heap, free'ing a stack
value or global value will corrupt the heap, free'ing a misaligned ptr
will corrupt the heap, etc, etc.
Which is why any implementor worth a grain of salt will make a
better system.

My company, Dynamic Memory Solutions, markets Dynamic Leak Check that
checks for these sorts of errors, www.dynamic-memory.com. Dynamic Leak
Check has a custom allocator that catches error but is significantly
than the standard allocator.

Matthew
Dynamic Memory Solutions
www.dynamic-memory.com


I suggest you improve your knowledge before selling your software.

--
"A man who is right every time is not likely to do very much."
-- Francis Crick, co-discover of DNA
"There is nothing more amazing than stupidity in action."
-- Thomas Matthews
Nov 14 '05 #35

P: n/a
<Je***********@physik.fu-berlin.de> wrote in message
news:2p************@uni-berlin.de...
Mabden <mabden@sbc_global.net> wrote:
"dbtid" <db***@dev.null.us> wrote in message
news:MF********************@fe2.columbus.rr.com...
> int* p = (int*)malloc(n*sizeof(int));

Why, OH WHY, would you cast malloc?????

I thought you HAD to cast malloc(). Malloc() returns a void pointer.

...am I going insane (again)?


Are you serious? See the FAQ section 7.7. If that doesn't convince
you see the errata page for K&R2 where they retract their original
recommedation to cast the return value malloc().


Yes, I am serious in my statement. Doesn't malloc() return a void pointer
which can't be used until cast to something "real"? Or are we assuming
implicit casting is better than explict casting? Why?

Post a link to the FAQ and I'll read it. You might think about that when you
tell someone to read it. Duh.

"errata page for K&R2"?? That doesn't parse. ;-) Tough crowd. These are the
jokes folks...

--
Mabden
Nov 14 '05 #36

P: n/a
man,
I still did not got my answer .... while freeing the memory how free()
knows how many bytes to be freed caz we pass only pointer to the
allocated area....
"E. Robert Tisdale" <E.**************@jpl.nasa.gov> wrote in message news:<ch**********@nntp1.jpl.nasa.gov>...
Mabden wrote:
dbtid wrote:
int* p = (int*)malloc(n*sizeof(int));

Why, OH WHY, would you cast malloc?????


I thought you HAD to cast malloc().


You do in C++ but not in C.
Suyog_Linux cross posted to both comp.lang.c and comp.lang.c++
so I posted an example that both C and C++ compilers should accept.
Malloc() returns a void pointer.
...am I going insane (again)?


Probably.

Nov 14 '05 #37

P: n/a
Suyog_Linux wrote:
man,
I still did not got my answer .... while freeing the memory how free()
knows how many bytes to be freed caz we pass only pointer to the
allocated area....


Several people have already answered - "it depends on the
implementation".

--
Chris "electric hedgehog" Dollin
C FAQs at: http://www.faqs.org/faqs/by-newsgrou...mp.lang.c.html
C welcome: http://www.angelfire.com/ms3/bchambl...me_to_clc.html
Nov 14 '05 #38

P: n/a
Mabden wrote:
<Je***********@physik.fu-berlin.de> wrote in message
news:2p************@uni-berlin.de...

Are you serious? See the FAQ section 7.7. If that doesn't convince
you see the errata page for K&R2 where they retract their original
recommedation to cast the return value malloc().
Yes, I am serious in my statement. Doesn't malloc() return a void pointer
which can't be used until cast to something "real"? Or are we assuming
implicit casting is better than explict casting? Why?


There's no such thing as "implicit casting" in C.

The void* value returned by malloc can be used without having to cast it.
(In fact, it can be used [1] without having to convert it, too.)
Post a link to the FAQ and I'll read it.
What, Google has suddenly stopped working?
You might think about that when you tell someone to read it. Duh.
Probably they did, and assumed that you'd be able to find it.
"errata page for K&R2"?? That doesn't parse.
It's a noun phrase. Although I suppose it could be construed as an
imperative, but I'd prefer it with a comma then.
;-) Tough crowd. These are the jokes folks...


No, there are the *real* folks. The jokes folks are standing up over
there. (The int folks are inside, and the char folks are starting a
fire. The double folks are going to work on TV, and the float folks
have gone for a swim. The long folks have moved to Tertius, and the
short folks are collecting pennies for the battery. I can't tell where
the unsigned folks have gone. I won't go near a void folk, anyway.)

[1] For some value of "used".

--
Chris "electric hedgehog" Dollin
C FAQs at: http://www.faqs.org/faqs/by-newsgrou...mp.lang.c.html
C welcome: http://www.angelfire.com/ms3/bchambl...me_to_clc.html
Nov 14 '05 #39

P: n/a
Mabden <mabden@sbc_global.net> wrote:
<Je***********@physik.fu-berlin.de> wrote in message
news:2p************@uni-berlin.de...
Mabden <mabden@sbc_global.net> wrote:
> "dbtid" <db***@dev.null.us> wrote in message
> news:MF********************@fe2.columbus.rr.com...
>> > int* p = (int*)malloc(n*sizeof(int));
>>
>> Why, OH WHY, would you cast malloc?????
> I thought you HAD to cast malloc(). Malloc() returns a void pointer.

> ...am I going insane (again)?


Are you serious? See the FAQ section 7.7. If that doesn't convince
you see the errata page for K&R2 where they retract their original
recommedation to cast the return value malloc().

Yes, I am serious in my statement. Doesn't malloc() return a void pointer
which can't be used until cast to something "real"? Or are we assuming
implicit casting is better than explict casting? Why?
Yes, malloc() returns a void pointer and that gets automatically
converted to the type on the left hand side of the assignment.
An explicit cast will keep the compiler from complaining (even
with reasonably warning level settings) if one forgets to include
<stdlib.h>. Such a mistake makes the compiler assumes that malloc()
returns an int and that can (see e.g. a previous thread about the
general non-possibility of casting between integer and pointer types)
lead to the return value becoming garbled (an example recently dis-
cussed here was about this problem on IA64 based machines). An explicit
cast only is reasonable (and required) if you either try to compile
with a C++- or a pre-ANSI C-compiler.
Post a link to the FAQ and I'll read it. You might think about that when you
tell someone to read it. Duh.
Sorry, but since you've been posting here since several months I was
assuming that wouldn't be necessary in your case.

CLC FAQ <http://www.eskimo.com/~scs/C-faq/top.html>
"errata page for K&R2"?? That doesn't parse. ;-) Tough crowd. These are the
jokes folks...


The web page with errata for the book "The C programming language",
2nd. ed. by Mrs. Kernighan and Ritchie is at

<http://cm.bell-labs.com/cm/cs/cbook/2ediffs.html>

They write there

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.

Regards, Jens
--
\ Jens Thoms Toerring ___ Je***********@physik.fu-berlin.de
\__________________________ http://www.toerring.de
Nov 14 '05 #40

P: n/a
"Mabden" <mabden@sbc_global.net> wrote in message
news:Nu******************@newssvr29.news.prodigy.c om...
<Je***********@physik.fu-berlin.de> wrote in message
news:2p************@uni-berlin.de...
Mabden <mabden@sbc_global.net> wrote:
I thought you HAD to cast malloc(). Malloc() returns a void pointer.
...am I going insane (again)?


Are you serious? See the FAQ section 7.7. If that doesn't convince
you see the errata page for K&R2 where they retract their original
recommedation to cast the return value malloc().


Yes, I am serious in my statement. Doesn't malloc() return a void pointer
which can't be used until cast to something "real"? Or are we assuming
implicit casting is better than explict casting? Why?


Casts are not implicit or explicit, conversions are. A cast is an explicit
conversion. As for why not to cast, see Ben Pfaff's reply to your earlier
post.

HTH,
Alex
Nov 14 '05 #41

P: n/a
Je***********@physik.fu-berlin.de wrote:
The web page with errata for the book "The C programming language",
2nd. ed. by Mrs. Kernighan and Ritchie is at ^^^^
The plural of 'Mr.' is 'Messrs'. You have inflicted a gender-change on
at least BWK, and, if 'Mrs.' distributes over conjunction, on DMR as well.
<http://cm.bell-labs.com/cm/cs/cbook/2ediffs.html>

Nov 14 '05 #42

P: n/a
Suyog_Linux wrote:
I wish to know how the free()function knows how much memory to be
freed as we only give pointer to allocated memory as an argument to
free(). Does system use an internal variable to store allocated memory
when we use malloc().
Plz help......


A simple implementation, one of many solutions.

char memory[0x2000]; //in real code, this would
// point to all the availiable memory in the area.
// this char array will represent the memory availiable

int mem_size = 0x2000;

struct Header{
struct Header *next;
int size;
};

struct Header start;
start.next = NULL;
start.size = mem_size;

void *malloc(int size){
struct Header *i;
//find first availiable block
// Dont use this
// just an example code that i typed up without testing
for(i = &start; size > i->size && i!=NULL ; i = i->next);

//change the header values to reflect what we have
i->size -= (size + sizeof(Header));

//create a new header at the end
struct Header *toreturn = (struct Header *)((int)i + i->size);
toreturn->size = size;
toreturn->next = NULL; //Null means block is used

//return a pointer to the end of the header, allocate from
// back to the front
return toreturn + sizeof(Header);
}

void free(void * tofree){
struct Header h = (int) tofree - sizeof(Header);
struct Header i;

//find the end of the linked list
for(i=start; i.next!=NULL; i = i->next);
//add this block to the linked list
i->next = h;
h->next = NULL;
}

Note, the method i posted is a truely horrible code, but it is like that
for simplicity because it is easier for me to type, and second, you
probably understand it more without all the checks. There are a number
of things that will definitly go wrong if the code is used, so don't
bother trying.
Nov 14 '05 #43

P: n/a
<Je***********@physik.fu-berlin.de> wrote in message
news:2p************@uni-berlin.de...
Mabden <mabden@sbc_global.net> wrote:
<Je***********@physik.fu-berlin.de> wrote in message
news:2p************@uni-berlin.de...
Mabden <mabden@sbc_global.net> wrote:
> "dbtid" <db***@dev.null.us> wrote in message
> news:MF********************@fe2.columbus.rr.com...
>> > int* p = (int*)malloc(n*sizeof(int));
>>
>> Why, OH WHY, would you cast malloc?????
> I thought you HAD to cast malloc(). Malloc() returns a void pointer.
> ...am I going insane (again)?

Are you serious? See the FAQ section 7.7. If that doesn't convince
you see the errata page for K&R2 where they retract their original
recommedation to cast the return value malloc().
Yes, I am serious in my statement. Doesn't malloc() return a void
pointer which can't be used until cast to something "real"? Or are we assuming
implicit casting is better than explict casting? Why?


Yes, malloc() returns a void pointer and that gets automatically
converted to the type on the left hand side of the assignment.
An explicit cast will keep the compiler from complaining (even
with reasonably warning level settings) if one forgets to include
<stdlib.h>. Such a mistake makes the compiler assumes that malloc()
returns an int and that can (see e.g. a previous thread about the
general non-possibility of casting between integer and pointer types)
lead to the return value becoming garbled (an example recently dis-
cussed here was about this problem on IA64 based machines). An explicit
cast only is reasonable (and required) if you either try to compile
with a C++- or a pre-ANSI C-compiler.


Small comfort. Since when when does C not "Trust the programmer". Have your
new C99 standards or whatever done something to make a malloc return cast
something I control, into something it controls?

Or are you just saying that It is yet another thing "I don't need to worry
about" because we've changed C into a "better language"?"
Post a link to the FAQ and I'll read it. You might think about that when you tell someone to read it. Duh.


Sorry, but since you've been posting here since several months I was
assuming that wouldn't be necessary in your case.

CLC FAQ <http://www.eskimo.com/~scs/C-faq/top.html>


Need one repeat the "ASSUME" problem? In addition, not all threads are
available to all people. I have now bookmarked it. If, in 5 years it is
somwhere else, will you assume I know where it is then?
"errata page for K&R2"?? That doesn't parse. ;-) Tough crowd. These are the jokes folks...
The web page with errata for the book "The C programming language",
2nd. ed. by Mrs. Kernighan and Ritchie is at

<http://cm.bell-labs.com/cm/cs/cbook/2ediffs.html>


Thank you, I will look and update my book as apropos.

They write there

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.


Unless I'm stupid, and I have been assured I am, it says old programs need
the cast and new C++ programs need the cast, and nobody is hurt if you cast
it now either.

So, how am I wrong?

--
Mabden
Nov 14 '05 #44

P: n/a
Mabden <mabden@sbc_global.net> wrote:
Small comfort. Since when when does C not "Trust the programmer". Have your
new C99 standards or whatever done something to make a malloc return cast
something I control, into something it controls?
The automatic conversion is part of the C89 standard, so it's been
this way since about 15 years. And the language doesn't keep you
from casting, but it does not required it - which was what you
seemed to assume when you wrote:
I thought you HAD to cast malloc(). Malloc() returns a void pointer. Or are you just saying that It is yet another thing "I don't need to worry
about" because we've changed C into a "better language"?"
I don't know whom you mean by "we" but I at least took no part in
writing the C89 (or C99) standard.
> Post a link to the FAQ and I'll read it. You might think about that when you > tell someone to read it. Duh.


Sorry, but since you've been posting here since several months I was
assuming that wouldn't be necessary in your case.

CLC FAQ <http://www.eskimo.com/~scs/C-faq/top.html> Need one repeat the "ASSUME" problem? In addition, not all threads are
available to all people. I have now bookmarked it. If, in 5 years it is
somwhere else, will you assume I know where it is then?
Well, it's typically assumed that people read the FAQ before posting
here and its URL is in the signature of at least half a dozend regular
posters. But perhaps I did assume too much... If you can't find it any
other way google as well as several other search engines like yahoo,
altavista etc. return it as the very first result for "C FAQ".
<http://cm.bell-labs.com/cm/cs/cbook/2ediffs.html> Thank you, I will look and update my book as apropos. They write there

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.

Unless I'm stupid, and I have been assured I am, it says old programs need
the cast and new C++ programs need the cast, and nobody is hurt if you cast
it now either.


Are you also still writing function arguments like this?

main( argc, argv )
int argc;
char *argv[];
{
....

Pre-C89 compilers did require that, but I would guess they aren't used
too often anymore for at least 10 years... And if I need to write C++
I wouldn't use malloc(), free() etc. but the new and delete operators.

--
\ Jens Thoms Toerring ___ Je***********@physik.fu-berlin.de
\__________________________ http://www.toerring.de
Nov 14 '05 #45

P: n/a
E. Robert Tisdale wrote on 03/09/04 :
Ben Pfaff wrote:
I don't recommend casting the return value of malloc():

* Casting its return value can mask a failure to #include
<stdlib.h>, which leads to undefined behavior.
Only if you have a lame compiler:

// #include <stdlib.h>
int* p = (int*)malloc(n*sizeof(int));
> gcc -Wall -std=c99 -pedantic -o main main.c main.c: In function `main':
main.c:7: warning: implicit declaration of function `atoi'
main.c:8: warning: implicit declaration of function `malloc'


The compiler can be 'not lame', but badly tuned.
gcc -std=c99 -o main main.c


--
Emmanuel
The C-FAQ: http://www.eskimo.com/~scs/C-faq/faq.html
The C-library: http://www.dinkumware.com/refxc.html

"C is a sharp tool"

Nov 14 '05 #46

P: n/a
Mabden wrote on 03/09/04 :
I thought you HAD to cast malloc(). Malloc() returns a void pointer.
...am I going insane (again)?
Are you serious? See the FAQ section 7.7. If that doesn't convince
you see the errata page for K&R2 where they retract their original
recommedation to cast the return value malloc().


Yes, I am serious in my statement. Doesn't malloc() return a void pointer


It does.
which can't be used until cast to something "real"? Or are we assuming
implicit casting is better than explict casting? Why?
void* is implicitely compatible with all pointer to objects. Implicit
cast can be better for reasons previously mentionned.
"errata page for K&R2"?? That doesn't parse. ;-) Tough crowd. These are the
jokes folks...


http://cm.bell-labs.com/cm/cs/cbook/2ediffs.html

--
Emmanuel
The C-FAQ: http://www.eskimo.com/~scs/C-faq/faq.html
The C-library: http://www.dinkumware.com/refxc.html

"C is a sharp tool"

Nov 14 '05 #47

P: n/a
Mabden wrote on 04/09/04 :
CLC FAQ <http://www.eskimo.com/~scs/C-faq/top.html>


Need one repeat the "ASSUME" problem? In addition, not all threads are
available to all people. I have now bookmarked it. If, in 5 years it is
somwhere else, will you assume I know where it is then?


Google knows. Type "clc faq" and press "I'm lucky"...
They write there

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.


Unless I'm stupid, and I have been assured I am, it says old programs need
the cast and new C++ programs need the cast, and nobody is hurt if you cast
it now either.

So, how am I wrong?


Correct. But programmers with a functionnal brain don't use pre-ANSI
compilers (when possible) and don't compiler their code with a non-C
compiler.

Consequently the cases where the cast is necessary tend to vanish.

--
Emmanuel
The C-FAQ: http://www.eskimo.com/~scs/C-faq/faq.html
The C-library: http://www.dinkumware.com/refxc.html

"C is a sharp tool"

Nov 14 '05 #48

P: n/a
Suyog_Linux wrote on 03/09/04 :
man,
I still did not got my answer .... while freeing the memory how free()
knows how many bytes to be freed caz we pass only pointer to the
allocated area....


- It's an implementation issue. (Easy to imagine that the address of
the block gives access to some hidden information like the real size of
the allocated block...)
- Why in the world would you need such an information ?

--
Emmanuel
The C-FAQ: http://www.eskimo.com/~scs/C-faq/faq.html
The C-library: http://www.dinkumware.com/refxc.html

"C is a sharp tool"

Nov 14 '05 #49

P: n/a
Emmanuel Delahaye <em***@YOURBRAnoos.fr> writes:
void* is implicitely compatible with all pointer to objects.


....as long as the pointers to objects are not qualified with
const, volatile, or restrict.
--
"Given that computing power increases exponentially with time,
algorithms with exponential or better O-notations
are actually linear with a large constant."
--Mike Lee
Nov 14 '05 #50

74 Replies

This discussion thread is closed

Replies have been disabled for this discussion.