1

I am reading in a book that the malloc function in C takes the number of 'chunks' of memory you wish to allocate as a parameter and determines how many bytes the chunks are based on what you cast the value returned by malloc to. For example on my system an int is 4 bytes:

int *pointer;

pointer = (int *)malloc(10);

Would allocate 40 bytes because the compiler knows that ints are 4 bytes.

This confuses me for two reasons:

  1. I was reading up, and the size parameter is actually the number of bytes you want to allocate and is not related to the sizes of any types.

  2. Malloc is a function that returns an address. How does it adjust the size of the memory it allocated based on an external cast of the address it returned from void to a different type? Is it just some compiler magic I am supposed to accept?

I feel like the book is wrong. Any help or clarification is greatly appreciated!

Here is what the book said:

char *string;
string = (char *)malloc(80);

The 80 sets aside 80 chunks of storage. The chunk size is set by the typecast, (char *), which means that malloc() is finding storage for 80 characters of text.

Matt Vaughan
  • 1,135
  • 2
  • 13
  • 19
  • Which book are you reading that has that somewhat eccentric view of how memory allocation works? – Jonathan Leffler Apr 06 '13 at 04:22
  • C All-In-One Desk Reference for Dummies... I like the for dummies series :) – Matt Vaughan Apr 06 '13 at 04:26
  • 4
    If it gets this wrong, it's hard to predict what else is wrong. Time to identify the book (so we can blacklist it) and go get yourself a better one. _[...time passeth...]_ Apparently, it is a 'For Dummies' book; in this case, written 'By Dummies' too. Throw it forcefully out of the window or into the trash and get something better. The 'chunk size' is 'a byte' or `sizeof(char)`; the cast cannot affect the behaviour of the call. – Jonathan Leffler Apr 06 '13 at 04:26
  • 6
    I contacted the author of that book a few years back, after finding about 100 errors in the first 50 pages. He told me, paraphrasing, to "get a life", the mistakes didn't matter, and I shouldn't take coding so seriously. – Randy Howard Apr 06 '13 at 04:30
  • It's on Kindle. What do I do!? – Matt Vaughan Apr 06 '13 at 04:30
  • 2
    Delete it before it pollutes the device further. :) – Randy Howard Apr 06 '13 at 04:31
  • @RandyHoward Is it Dan Gookin? Because I know what you mean. There are many errors that if I didn't have experience in other languages would throw me off. – Matt Vaughan Apr 06 '13 at 04:32
  • By "the author of that book", I think @RandyHoward means the author of the book you named -- who is indeed Dan Gookin. "I like the for dummies series" -- Some of them are good; this one obviously isn't. – Jim Balter Apr 06 '13 at 04:44
  • 4
    I am appalled that this book has a 5-star rating on Amazon. – jamesdlin Apr 06 '13 at 07:10
  • 1
    Please take the time to post a review on Amazon. Might as well take Clive Feather's [classic review](http://www.lysator.liu.se/c/schildt.html) of Schildt's "The annotated ANSI C standard" as a model... – vonbrand Apr 08 '13 at 00:13

2 Answers2

8

Yes the book is wrong and you are correct please throw away that book.
Also, do let everyone know of the name of the book so we can permanently put it in our never to recommend black list.

Good Read:
What is the Best Practice for malloc?

Community
  • 1
  • 1
Alok Save
  • 202,538
  • 53
  • 430
  • 533
7

When using malloc(), use the sizeof operator and apply it to the object being allocated, not the type of it.

Not a good idea:

int *pointer = malloc (10 * sizeof (int)); /* Wrong way */ 

Better method:

int *pointer = malloc (10 * sizeof *pointer);

Rationale: If you change the data type that pointer points to, you don't need to change the malloc() call as well. Maintenance win.

Also, this method is less prone to errors during code development. You can check that it's correct without having to look at the declaration in cases where the malloc() call occurs apart from the variable declaration.

Regarding your question about casting malloc(), note that there is no need for a cast on malloc() in C today. Also, if the data type should change in a future revision, any cast there would have to be changed as well or be another error source. Also, always make sure you have <stdlib.h> included. Often people put in the cast to get rid of a warning that is a result from not having the include file. The other reason is that it is required in C++, but you typically don't write C++ code that uses malloc().

The exact details about how malloc() works internally is not defined in the spec, in effect it is a black box with a well-defined interface. To see how it works in an implementation, you'd want to look at an open source implementation for examples. But malloc() can (and does) vary wildly on various platforms.

Randy Howard
  • 2,165
  • 16
  • 26