Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Also check realloc() if shrinking allocated size of memory?

Tags:

c++

c

realloc

When you call realloc() you should check whether the function failed before assigning the returned pointer to the pointer passed as a parameter to the function...

I've always followed this rule.

Now is it necessary to follow this rule when you know for sure the memory will be truncated and not increased?

I've never ever seen it fail. Just wondered if I could save a couple instructions.

like image 439
user3141117 Avatar asked Dec 20 '22 17:12

user3141117


2 Answers

realloc may, at its discretion, copy the block to a new address regardless of whether the new size is larger or smaller. This may be necessary if the malloc implementation requires a new allocation to "shrink" a memory block (e.g. if the new size requires placing the memory block in a different allocation pool). This is noted in the glibc documentation:

In several allocation implementations, making a block smaller sometimes necessitates copying it, so it can fail if no other space is available.

Therefore, you must always check the result of realloc, even when shrinking. It is possible that realloc has failed to shrink the block because it cannot simultaneously allocate a new, smaller block.

like image 83
nneonneo Avatar answered Dec 22 '22 05:12

nneonneo


Even if you realloc (read carefully realloc(3) and about Posix realloc please) to a smaller size, the underlying implementation is doing the equivalent of malloc (of the new smaller size), followed by a memcpy (from old to new zone), then free (of the old zone). Or it may do nothing... (e.g. because some crude malloc implementations maitain a limited set of sizes -like power of two or 3 times power of two-, and the old and new size requirements fits in the same size....)

That malloc can fail. So realloc can still fail.

Actually, I usually don't recommend using realloc for that reason: just do the malloc, memcpy, free yourself.

Indeed, dynamic heap memory functions like malloc rarely fail. But when they do, chaos may happen if you don't handle that. On Linux and some other Posix systems you could setrlimit(2) with RLIMIT_AS -e.g. using bash ulimit builtin- to lower the limits for testing purposes.

You might want to study the source code implementations of C memory management. For example MUSL libc (for Linux) is very readable code. On Linux, malloc is often built above mmap(2) (the C library may allocate a large chunk of memory using mmap then managing smaller used and freed memory zones inside it).

like image 36
Basile Starynkevitch Avatar answered Dec 22 '22 05:12

Basile Starynkevitch