2004-06-30 09:36:14

by jan

[permalink] [raw]
Subject: malloc overlap?

This question is probably misplaced - sorry about that, but one has to start somewhere, and I think it isn't too far out. Here goes:

I am developing a program that mallocs a struct, which contains a pointer to another struct, which gets malloced. Then I realloc the first buffer to be one element larger and assign something to an element in the second element - and this action overwrites part of the second level struct. After much tracing I am now sure that the buffers somehow have come to overlap. Is this a known error? I imagine that if the kernel had this kind of problem, it wouldn't run far, but surely memory allocation is handled in the kernel?

I hope somebody can point me in the right direction - and thank you for helping! I am not on the list, so please reply directly.

/jan



2004-06-30 09:54:46

by Sean Neakums

[permalink] [raw]
Subject: Re: malloc overlap?

[email protected] writes:

> I am developing a program that mallocs a struct, which contains a
> pointer to another struct, which gets malloced. Then I realloc the
> first buffer to be one element larger and assign something to an
> element in the second element - and this action overwrites part of the
> second level struct. After much tracing I am now sure that the buffers
> somehow have come to overlap. Is this a known error? I imagine that if
> the kernel had this kind of problem, it wouldn't run far, but surely
> memory allocation is handled in the kernel?

malloc is implemented in userspace, typically by the C library, which
uses lower-elvel mechanisms to obtain memory from the kernel.

How are you calling realloc? It must be called thus:

x = realloc(x, s);

since the block will have to be moved if there is no space after it
into which to expand. Given that you allocated the block at x,
another block, and then expanded the block at x, I think this may be
what's happening.