Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is malloc deterministic?

Tags:

c

linux

malloc

x86

gcc

Is malloc deterministic? Say If I have a forked process, that is, a replica of another process, and at some point both of them call the malloc function. Would the address allocated be the same in both processes? Assuming that other parts of execution are also deterministic.

Note: Here, I'm only talking about virtual memory, not physical one.

like image 224
MetallicPriest Avatar asked Nov 17 '11 16:11

MetallicPriest


People also ask

Is dynamic memory allocation deterministic?

Dynamic memory allocation tends to be non-deterministic; the time taken to allocate memory may not be predictable and the memory pool may become fragmented, resulting in unexpected allocation failures. This article details the problems and an approach to deterministic dynamic memory allocation.

Why you shouldn't use malloc?

There are a number of reasons why malloc() is not generally recommended for embedded applications: The function is commonly not re-entrant (thread friendly), so using it with a real-time operating system may be challenging.


1 Answers

There is no reason at all for it to be deterministic, in fact there can be some benefit to it not being deterministic, for example increasing the complexity of exploiting bugs (see also this paper).

This randomness can be helpful at making exploits harder to write. To successfully exploit a buffer overflow you typically need to do two things:

  1. Deliver a payload into a predictable/known memory location
  2. Cause execution to jump to that location

If the memory location is unpredictable making that jump can become quite a lot harder.

The relevant quote from the standard §7.20.3.3/2:

The malloc function allocates space for an object whose size is specified by size and whose value is indeterminate

If it were the intention to make it deterministic then that would be clearly stated as such.

Even if it looks deterministic today I wouldn't bet on it remaining so with a newer kernel or a newer libc/GCC version.

like image 77
Flexo Avatar answered Sep 19 '22 11:09

Flexo