Allocation and release of memory

My question is pretty simple. Usually we allocate memory by declaring a pointer, and then assigning a block of memory to that pointer. Suppose somewhere in the code I use

ptr = ptr + 1

and then i use

free(ptr)

can someone say what will happen. The entire memory block will be freed or something else. Can I partially free the memory?

+4
source share
4 answers

You should always pass in exactly the same pointer to free that you received from malloc (or realloc .) If you do not, the “undefined behavior”, which is an art term, means that you cannot rely on the behavior of the program for any in a predictable way. In this case, however, you should expect it to work immediately. (If you are unlucky, this will damage the memory, which will lead to a crash after a while or, even worse, to an incorrect output.)

The only way to partially free memory is to realloc with a smaller size, but it is only useful for trimming at the end and does not guarantee that the cut piece is available for some other allocation.

+7
source

Unable to free part of memory block. The only thing you can do is redistribute the block, giving it a different size. However, this does not guarantee that the block will be in one place in memory (it can be copied somewhere else).

+1
source

You must pass the free () to the same pointer to the same place malloc (). This is because the allocator keeps a list of lists of blocks you have allocated (@everyone: feel free to add / change if I'm wrong), and if the pointer you pass for free doesn't compare it, this free () list complains ("Bad memory block ", may be?). To partially free memory, you must use realloc (), which resizes this memory block, but is slow and inefficient. You should use it only when you are confident in the new block size or leave more space to fill in the future.

+1
source

malloc (), free () and realloc () are not part of C.

These functions are defined in the standard library. The code in the standard library that deals with it is usually called the "dispenser." So the actual answer is: "It depends on the C library."

On Linux, glibc will crash the program. In VC ++, C runtime will damage the state of the dispenser

The source code is available for these libraries, so you can actually set a breakpoint and make the step free.

+1
source

Source: https://habr.com/ru/post/1344788/


All Articles