Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Allocating and freeing memory

Tags:

c

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?

like image 341
bubble Avatar asked Jan 21 '23 04:01

bubble


1 Answers

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.

like image 72
zwol Avatar answered Feb 04 '23 06:02

zwol