I am curious of how malloc() actually allocates memory. I am reading C programming by K.N.King for reference. In particular, chapter 17. Initially in the chapter void *malloc(size_t size) is described as function which allocates a block of memory of size bytes and returns a void * pointer to this memory block. Two main applications being dynamically allocating strings and arrays. When malloc() is called the returned pointer will be cast to the appropriate type, for example in,
int *n;
n = malloc(sizeof(*n));
the malloc() return will be cast to (int *). It was my understanding that since this cast occurs the memory block allocated by the call of malloc() contains uninitialised integers. However, after more reading in the chapter I think I am wrong but I can't figure out exactly what is going on.
The conflict in understanding occurred when reading the last section of the chapter on flexible array members. The idea of defining a structure with the last member being "incomplete", i.e.,
struct vstring {
int len;
char chars[];
};
The author then goes on to say, and I quote:
A structure that contains a flexible array member is an incomplete type. An incomplete type is missing part of the information needed to determine how much memory it requires. ... In particular, an incomplete type can't be a member of another structure or an element of an array. However, and array may contains pointers to structure that have a flexible array member.
So clearly my earlier understand must be flawed otherwise a call such as,
struct vstring *str = malloc(sizeof(struct vstring) + n);
would allocate an array containing an incomplete type.
Is the block of memory allocated by malloc() an array of a particular type after being cast? If not, then how can the following work,
struct node {
int value;
struct node *next;
};
struct node *new_node = malloc(sizeof(*new_node));
new_node->value = 10;
if the memory allocated by the malloc() call is not declared as elements of struct node? Even the integer array example I put at the beginning of the post, I would be able to access the elements of the the allocated memory by subscripting n immediately.
mallocis implemented is operating system specific. On Linux, it often uses mmap(2) and you could download then study the source code of musl libc or of GNU libc. Learn also to use valgrindsizeofoperator.chars[]prior to explicitly allocating memory to the structure. In that sense, is the structure not an incomplete type? In particular, this would imply that the compiler doesn't know the number of bytes required for the structure andsizeof(struct vstring)would fail?