简体   繁体   中英

Is this is correct about malloc() and calloc()?

I have researched in all possible ways I could but it's hard for me to digest the fact that both malloc ie malloc(sizeof(10)) and calloc ie calloc(2,sizeof(5)) allocates same contiguous memory, ignoring the other facts that calloc initializes to zero and works relatively slower than malloc. so this is what I think.

I think that on a 32-bit system if we call malloc and say malloc(sizeof(10)) then malloc will go to the heap and allocate 12 bytes of memory, because for a 32-bit system the memory packages are arranged in groups of 4 bytes so to allocate 10 bytes 3 blocks are needed with a padding of 2 bytes in the last block.

Similarly, if we call calloc and say calloc(2,sizeof(5)) then it will allocate 2 blocks each of size 8 bytes and in total 16 bytes because due to the same reason that memory is in the packages of 4 bytes and to allocate 5 bytes two blocks of 4 bytes are used and in one block a padding of 3 bytes will be provided.

So this is what I think of malloc and calloc. I may be right or wrong but please tell me either way.

calloc allocates "memory for an array of nmemb elements of size bytes each" ( Linux man page ), but we know that arrays in C cannot have padding between array elements, they must be contiguous in memory. On the other hand, malloc allocates " size bytes", so either of malloc(10) or calloc(2,5) will give you those ten bytes.

Now, what happens behind the scenes is another issue, the C library might decide to allocate 12, 16, or 42 bytes instead. But you can't and must not count on that. If you ask for 10 bytes, assume you got 10.

malloc(sizeof(10)) is different, it takes the size in memory of an int (since 10 is an int ), and allocates that much.

What you get when you use both methods is at least that amount of memory you request. It can be more. One reason could be the one you are mentioning. Another reason can be that you get a bigger chunk just in case you want to change it later.

There's no way to say exactly how much you got. Only that you are guaranteed at least what you requested, and if you don't, you'll get a null pointer.

Note though, that with get I mean that you get what you ask for, and you can NEVER count on more than that. That will be undefined behavior.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM