Reputation: 30815
What I want is to have the forked process, which is copy of its parent process, to get the same addresses returned from each malloc function call, as its parent process. How can I achieve this?
Actually what I am trying to achieve is to have two replicated processes, which execute the same thing. I am basically doing this to detect soft errors, that is, if there is any divergence, it must be due to an error, not non-determinism. Now, since malloc is non-deterministic, it will make the two processes diverge, which I want to avoid.
If that is not possible, can I log addresses returned by malloc for the parent process and use the same addresses for the forked process. Would this work?
Upvotes: 3
Views: 343
Reputation: 72717
You can't do this with the standard malloc
. But you can write your own custom allocator that has a deterministic way to allocate. E.g. as the allocation pool, use a sufficiently sized static char pool[POOL_SIZE];
The address of pool
remains invariant across a fork()
. All pointers into pool
as well. Voilà!
Upvotes: 0
Reputation: 1
If your system is Linux, then you'll get more reproducible addresses by disabling the address space randomization. You can achieve that with this command (to be run as root)
echo 0 > /proc/sys/kernel/randomize_va_space
(but address space randomization is a feature which may improve your system security)
However, this don't guarantee that parent and child process will get the same behavior (because there is a small difference between them: the return of fork()
and their pid). And you cannot be sure that their allocation pattern is similar enough. Imagine if after the fork the (forked) program executes something like
char *p = malloc (8192*(3 + (getpid() % 10) + time(NULL) % 100));
then you should expect the malloc to request widely different sizes in parent and in child, with a different malloc returned address. So this contrieved example shows that your requirement is not realistic.
Upvotes: 3
Reputation: 755269
There is simply no way to do this with malloc
. The returned address of malloc
is not defined to be deterministic in any way (especially a portable one). To attempt to sync it up between process`s, even a child and parent one, is likely a fruitless effort.
Can you give us some more details on why you want to do this? Perhaps there is another way to achieve the effect you're looking for.
Upvotes: 2
Reputation: 28752
You probably want to use shared memory. You can't make malloc return the same value since once the first call executes, that memory has been allocated and can't be given to another process.
Upvotes: -2