Concept

How does malloc() allocate memory for a dynamic array?

ComputerScienceOne / Dynamic Memory

"Recall that static arrays have many shortcomings (see Section 7.2). In general they should be avoided since stack space is limited and they cannot be returned from functions. Fortunately, C provides several standard library functions that facilitate the creation and management of dynamically allocated arrays. The primary function to allocate memory is the memory allocation function, malloc():\n\nvoid * malloc(size_t size);\n\nwhich takes a single parameter, the number of bytes that you wish to allocate. The type, size_t is an alias for an unsigned integer type, so you can think of it as an integer. Thus, malloc(200) would allocate 200 bytes and return a pointer to the memory space. In some instances, the allocation may fail. For example, if the program or system has run out of available memory or you simply request too much. In the event of a failure, malloc() returns a NULL pointer. The returned value can thus be checked to see if the allocation was successful or not.\n\nWe don’t have to manually calculate how many bytes we need for an array of a particular size. The macro sizeof() can be used to determine the number of bytes any type of variable requires on a system. For example, sizeof(int) gives the number of bytes an int takes while sizeof(double) gives the number of bytes for a double, etc. Thus, if we want to allocate an array of 100 integers, we could call malloc() as malloc(100 * sizeof(int)); Using sizeof() is actually preferable as some systems may use a different number of bytes for various types.\n\nFinally, note the return type of malloc(): it is a void pointer. The malloc() function simply allocates chunks of memory. It doesn’t care that you intend to use the memory to store integers or floating-point numbers. Thus, malloc() returns a “generic” pointer, simply an address in memory. Once we have that pointer we can treat it as an integer pointer, int * or a floating-point pointer, double * depending on what we want to store. One way of doing this is to explicitly cast the void pointer as the pointer that we want. Some examples:\n\nint *arr = NULL;\n\ndouble *values = NULL;\n\narr = (int *) malloc(sizeof(int) * 10);\n\nvalues = (double *) malloc(sizeof(double) * 100);\n\nThe pointer cast is just like when we casted int types as double types so that we could perform division without truncation. In this case, we convert the returned generic void pointer into an int pointer and double pointer respectively."

Related Ideas

How does malloc() allocate memory for a dynamic array? | ComputerScienceOne | Bifalgorithm | Bifalgorithm