The C books keep talking about memory blocks, but I never understood what exactly they are. Is a memory block an array? A large memory cell? For example:
malloc(2*sizeof(int)); /*This allocates a block*/
A "memory block" is a contiguous chunk of memory.
An array in C is also a contiguous chunk of memory. However, using the less-generic term "array" has implications that the generic term "memory block" does not (you can, after all, have data of multiple types within a block, whereas the term "array" implies uniformity of use).
Using malloc
gives you memory dynamically -- the alternative is to allocate memory from the stack, as with int my_ints[2]
, but that doesn't give you control over the size of the block after your function is already running, or let you allocate more blocks after your function has started.
Also, stack size is relatively limited.
A memory block is a group of one or more contiguous chars ("bytes" - see note) of (real or virtual) memory.
The malloc(size_t size)
function allocates a memory block. The size
is how large (in chars) the block should be. Note that sizeof(int)
is the number of chars that an int
consumes, so malloc(2*sizeof(int));
allocates a memory block that is large enough to store 2 ints.
Because C is designed for many very different architectures; there's no guarantee that there's any relationship between things in different memory blocks. For example, you can't allocate 2 memory blocks and then calculate the difference between them (at least, not without relying on implementation defined behaviour).
For arrays, there must be a relationship between elements in the array; and for structures there must be a relationship between members of the structure. For this reason, each array and each structure must be contained within a memory block.
Note: Historically, char
was the smallest unit C handled, and "byte" was defined as 1 char (e.g. sizeof(char) == 1
), even if CHAR_BIT
happens to be something bizarre, like 9 or 16 or 32. Outside of C, "byte" has become synonymous with an 8-bit quantity, and is defined as an 8-bit unit in International standards (IEC 80000-13, IEEE 1541). The result of this is that the definition that C uses for "byte" is not an actual (International standard) byte, and it would be wrong to say that malloc()
allocates (International standard) bytes, but correct to say that malloc()
allocates chars or "non-standard things that were unfortunately called bytes by the C standard once upon a time".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With