0

What is the reason for using the functions that are allocating memory? (malloc , ExAllocatePool ,...)

If every variable or structure does not allocate memory to itself, then why do we use these functions?

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547
MDev
  • 3
  • 2
  • you can accept one of the answers by clicking on the grey checkmark below its score. You will be able to upvote once you get enough reputation. – chqrlie Jun 11 '22 at 19:29

2 Answers2

0

What is the reason for using the functions that are allocating memory?

The reason is simple. The same C source code might be used on small computers (mobile phones with a few megabytes) and on super computers (costing millions of €, with terabytes of memory).

Think also of software portability.

A typical example could be to sort an array of numbers. A cheap computer (perhaps the 2€ microprocessor inside your mouse) can sort just an array of a thousands int.

But a supercomputer could sort an array of ten billions int (that does not fit into your mobile phone).

For examples, look into the source code of GNU sort (or GNU make) or any textbook implementation of quicksort.

How would you code even a simple C compiler (like tinycc, which is open source) without allocating memory?

If every variable or structure does not allocate memory to itself, then why do we use these functions?

Every book on C programming is explaining why and how. See also this C reference.

As an exercise, code the C program which outputs the longest line in any given textual file. Input files could be small or huge (for example, the source code of sqlite) or the SQL dump of a huge PostGreSQL database.

See also (for Linux) my manydl.c program (generating arbitrarily big C code).

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547
0

There are many reasons to use memory allocation functions:

  • so programs can handle a variable amount of data: you could define fixed arrays of a maximum size, but it is more flexible to allocate the required memory once you know the amount needed for a given problem at runtime.

  • because some problems require a variable amount of memory depending on the actual data handled, even for a fixed amount data.

  • so memory used for a particular task can be reused for other purposes once the task has been completed.

chqrlie
  • 131,814
  • 10
  • 121
  • 189