Use extra space beyond what is reserved by "malloc"

1

When we request a quantity of memory to the system and we use much more than the requested what happens? I did this test and the code here compiled normally.

At first it worked as it should, I wanted to know what this implies, I believe that this is not something that is done, but for didactic purposes I wanted to understand about it.

int main(){
    player *p = (player*) malloc(5 * sizeof (player));

    for (int x=0;x<15;x++){
        p[x].id = 10 + x;

       std::cout << "Endereço: " << p + x<< std::endl;
    }

    for (int x=0;x<15;x++)
         std::cout << "Endereço: " << p + x << ", Valor: " << p[x].id << " ou " << (p + x)->id << std::endl;

    return 0;
}
    
asked by anonymous 09.04.2018 / 23:03

2 answers

1

When we use much more than the memory we allocate, simply the Operating System will not know that what is left belongs to your program and any other process can use this space, then in the middle of the program execution data that is beyond than what you have allocated can be modified and trashed. In Windows it usually does not give a compilation problem, but using a memory analysis tool like Valgrind , you will notice many errors.

Allocating Memory means telling the Operating System: "Protect a memory space for me sequentially, and give me the address of the beginning of this block you have allocated, because I already know the size and can manipulate manually, just protect this space so that no other process uses this memory until my process finishes or releases it. "

Releasing Memory is the opposite, you do not delete the data that is there, inclusive, knowing the address, if no other process has modified the data, it is possible that another process can access the data that was stored in the created address by another process , and this would be considered junk for other processes, whereas in the context of its execution it serves some purpose.

Releasing Memory is to say to the Operating System: "You can now allow any process to use memory space that starts at address X, size N"

    
09.04.2018 / 23:48
1
  

When we request a quantity of memory to the system and we use much more than the requested one what happens?

You write in an area not reserved for this and go over something else, obviously creating serious problems for the application since the value that was there is lost. The worst thing that can happen to you is working, because it is wrong, but it seems not. This is how much of a system invasion occurs.

In this case a problem has not happened because there is nothing else in memory, but no real code is like this.

In the same way that it did not release memory, in this case it does not matter, but in real code there might be problems.

Running is different from being right.

Generally, malloc() is not used in C ++.

    
09.04.2018 / 23:44