Delete a space allocated by malloc

4

First of all, I allocated 6 spaces of 52 bytes belonging to a struct in memory:

lista = malloc(6 * sizeof(registro));

In practice to access them via pointer is done:

lista[0], lista[1], lista[2]...

And how would I delete content stored in lista[2] space? Leaving the other 5 spaces intact?

    
asked by anonymous 02.11.2016 / 17:16

1 answer

0

When you make a malloc call, in simplified terms the OS keeps a record of the memory location that was delivered to you for use and how many bytes from it are available. So, doing something like free(&lista[2]) (missing the address indicator) does not work, because that address was not returned by a malloc call, just matches it in the 6 * 52 byte range from the registered address. p>

Vectors are contiguous spaces of memory, and not as flexible as lists. If you want to free up the space of lista[2] , the way is to do as Anthony quoted: relocate and move. But keep in mind that this changes the position of the original indexes and begins to be costly on large vectors.

Alternatively, there is a simpler solution: make a vector of pointers to struct. So each position of it would occupy a maximum of 8 bytes (which would only allow you to release at the end of the program if you are not too worried about memory) and would be right to do something like free(lista[2]) (in this case, you would not be releasing the position of the vector , but the address pointed to by the struct pointer in memory).

    
04.11.2016 / 15:22