bubble
bubble

Reputation: 3526

Allocating and freeing memory

My question is quite simple. We generally allocate memory by declaring a pointer and then assigning a block of memory to that pointer. Suppose somewhere in the code I happen to use

ptr = ptr + 1

and then I use

free(ptr)

can someone tell what will happen. The entire memory block will get deallocated or something else. Can I partially deallocate the memory?

Upvotes: 4

Views: 241

Answers (4)

Shamit Verma
Shamit Verma

Reputation: 3827

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

These are functions defines in standard library. Code in standard library that deals with it is usually called "allocator". So, actual answer is "It depends on C library".

On Linux, glibc would crash the program. On VC++, C runtime would corrupt allocator's state

Source code is available for these libraries, so you can actually put a breakpoint and step into free.

Upvotes: 1

BlackBear
BlackBear

Reputation: 22979

You must pass to free() the same pointer to the same location malloc() returned. That's because the allocator keeps a sort of list of the blocks you allocated (@everyone: feel free to add/modify if I'm wrong) and if the pointer you pass to free doesn't compare it this list free() complains ("bad memory block" maybe?). To partly deallocate the memory you should use realloc(), which changes the dimensions of that block of memory, but is slow and inefficient. You should use it only when you're sure of the new size of the block or leaving more space to fill in the future.

Upvotes: 1

julx
julx

Reputation: 9091

It's impossible to deallocate part of a memory block. The only thing you can do is reallocate the block giving it a different size. However this does not guarantee that the block will land in the same place in memory (it might be copied somewhere else).

Upvotes: 1

zwol
zwol

Reputation: 140445

You must always pass exactly the same pointer to free that you got from malloc (or realloc.) If you don't, the "behavior is undefined", which is a term of art that means you can't rely on the program behaving in any predictable way. In this case, though, you should expect it to crash immediately. (If you get unlucky, it will instead corrupt memory, causing a crash some time later, or worse, incorrect output.)

The only way to partially deallocate memory is realloc with a smaller size, but that's only good for trimming at the end and isn't guaranteed to make the trimmed-off chunk available for some other allocation.

Upvotes: 6

Related Questions