Bifalgorithm post · Computer science one · Dynamic Memory

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

How does malloc() allocate memory for a dynamic array? (Computer science one · Dynamic Memory) — "Recall that static arrays have many shortcomings (see Section…

Ideas in this flowchart

  • Allocation dynamique de tableaux en C avec malloc()
  • Les tableaux statiques présentent plusieurs inconvénients
  • L’espace de la pile est limité
  • Les tableaux statiques ne peuvent pas être retournés par des fonctions
  • La bibliothèque standard C facilite la création et la gestion des tableaux alloués dynamiquement
  • malloc() est la fonction principale d’allocation et prend en paramètre le nombre d’octets à réserver
  • size_t est un alias pour un type entier non signé
  • malloc() réserve l’espace demandé et renvoie un pointeur vers cette mémoire
  • L’allocation peut échouer si la mémoire disponible est insuffisante ou si la demande est trop grande
  • En cas d’échec, malloc() renvoie NULL, ce qui permet de vérifier la réussite de l’allocation
  • sizeof() détermine le nombre d’octets requis par un type ou une variable
  • Pour 100 entiers, on peut utiliser malloc(100 * sizeof(int))
  • L’utilisation de sizeof() s’adapte aux systèmes qui utilisent des tailles différentes pour les types
  • malloc() renvoie un pointeur void, c’est-à-dire une adresse mémoire générique
  • Le pointeur void peut être converti en pointeur du type voulu, comme int* ou double*
  • Des conversions explicites permettent notamment d’allouer des tableaux d’entiers ou de nombres réels
Feed/

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

No cover

Channel

Computer science one

1 page

"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."

Flowchart preview
👍
0
0 comments0 shares

Sign in to view and post comments.