Home > Blockchain >  Why is sizeof() used in the argument to malloc()?
Why is sizeof() used in the argument to malloc()?

Time:06-25

Like this is what the book showed me int *list = malloc(3 * sizeof(int))

But what's wrong with this? int *list = malloc(3)

My understanding says that malloc accepts "size" as a parameter and my goal is to only let pointer list to accept 3 values in it, but then why would I include sizeof(int) when using malloc?

CodePudding user response:

Let's look at this line of code:

int *list = malloc(3 * sizeof(int))

It creates a pointer to an int, and allocated three times the size of an int worth of memory for it. So we have enough room to store three ints in that block of memory.

I'll assume one int takes up four bytes of memory. So to store three of them, we need 12 bytes of memory (four bytes per int times three ints). malloc allocates space in bytes, so that will give you 12 bytes of memory (sizeof(int) will return four as there are four bytes per int*).

Now let's look at the other version:

int *list = malloc(3)

You allocate three bytes of memory. Sadly, one int is four bytes... so you have enough space for 3/4 of an int (again, assuming one int is four bytes). If you wanted to store three ints, you need to allocate memory equal to three times however big an int is, hence 3 * sizeof(int).


*Technically, there are platforms where an int isn't four bytes. So it is better to write sizeof(int) instead of 4. Don't worry about that for now, though.

CodePudding user response:

The parameter to malloc() is the number of bytes you want to allocate.

int* list = malloc(3) will only allocate 3 bytes

Each integer on a 32-bit platform is 32 bits (4 bytes). This can be obtained with sizeof(int)

An array of 3 integers will take 3*sizeof(int) which is 12 bytes on a 32-bit platform.

So

int* list = malloc(3*sizeof(int))

will allocate the space for 3 integers, which is 12 bytes on a 32-bit platform

  • Related