How to allocate memory ====================== [Published 2021-06-02] From the man page of malloc: The malloc() function allocates size bytes and returns a pointer to the allocated memory. allocate (from Wiktionary): 3. (computing) To reserve a portion of memory for use by a computer program. Does that mean that malloc reserves the memory? What does it mean to reserve memory? What does reserving memory do to the memory? Nothing. Malloc often doesn't change the memory in any way. Maybe reserving just means to decide that the memory will be used for something. Who makes the decision? The computer? No, computers don't have brains. The programmer does. The programmer allocates the memory, not malloc. That's because the programmer makes the decision that the memory will be used. The computer doesn't know anything about how things will be used. So what does malloc do then? It's a tool that programmers can use to manage memory allocations. That's all. What people call memory allocators should really be called memory allocation management tools. - - - - - How do you allocate memory then? Just think "This memory will be used." That's how you allocate memory. You don't even need to use memory allocation management tools. Here is a C program that shows how I can allocate memory and then use it without using any memory allocation management tools: #include #include int main() { char *my_string = (char *)1234; strcpy(my_string, "hello world"); printf("%s\n", my_string); } On the strcpy or printf line, is the memory that my_string points to allocated? It can be, if I say so. The only problem is that the program does not always work on some computers. That is not because the memory is not allocated; it is because the operating system usually stops you from accessing some random memory like that. That's why memory allocation management tools are useful. They do the work necessary to get permission to use memory from the operating system plus some additional work to keep track of what memory you have or haven't requested. Finally, there are multiple levels of allocation. On the hardware level, all of the memory in the computer is allocated to be used by the operating system (or possibly other things). At the same time, many memory addresses are allocated to other hardware parts than the memory; the tool used to keep track of these allocations is called a memory map and can be found in the computer's documentation. On the next level, some memory is allocated by the operating system to a running process; that's because the people who made the operating system intended that memory to be used by the process. Inside the process, some memory can be allocated to be used by the programmer who wrote that program. All of this means that the computer or compiler can't know what memory is allocated, so there are no memory safe languages (all languages allow you to access memory that you didn't intend to access).