Alfonso said:
Here is a snippet of one of the functions that causes the compiler to
barf (note the language is C++), but I'm not really doing anything C++
specific :
As Richard has already pointed out, those :: namespace operators
indicate that you certainly *are* doing something C++ specific!
SharedMemory::HEADER *p = NULL;
/* Code to alloc mem etc */
p = (SharedMemory::HEADER *) ((int)p + p->size); //offending line
What in the world are you trying to do here?! You're taking a
null pointer, casting it to an int, adding (I presume) another
int to it, and then trying to cast the result back to a pointer.
Moreover, unless I'm missing something, the int you're adding in
(that is, p->size) is fetched off of the null pointer you started
with. This doesn't look like it'll do anything useful, and it
*certainly* doesn't look like it'll allocate any memory!
I'm not sure I would have expected the compiler's first complaint
here to be about truncation of void * to int (in particular,
there aren't any void pointers in sight), but I'm glad it
complained about something, because you definitely need to
reexamine your thinking.
(There's an old rule, and it certainly applies here, that casts
should be used sparingly, and only when you know what you're
doing, and certainly not willy-nilly just to shut the compiler
up. In particular, you don't allocate memory by casting an int
to a pointer; you've got to call a memory-allocation function
somewhere! When the compiler complains about attempted
int-to-pointer conversions, and unless you're writing low-level
pointer manipulation code of the sort that only a linker ought to
be doing, the complaint almost invariably indicates that you're
mixing apples and oranges in an irreconciliable way, which the
insertion of a bunch of casts will only make worse.)
If the comment "Code to alloc mem etc" replaces some explicit
memory-allocation logic that is in your actual code; if p has
been appropriately set up to point at a SharedMemory::HEADER
object by the time you hit the line
p = (SharedMemory::HEADER *) ((int)p + p->size);
the problem may simply be that (int) cast, which is truncating a
pointer into an int (though the pointer it's truncating is a
SharedMemory::HEADER *, not a void *). What happens if you
remove both casts? That is, what happens if you use the
straightforward
p = p + p->size;
instead? That's normal-looking pointer arithmetic, and is
probably closer to what you want. The explicit casts make me
suspect that at some point you were either (a) trying to do the
pointer arithmetic in chunks of other than sizeof(SharedMemory::HEADER),
or (b) using void pointers which the compiler (correctly) wouldn't
let you do arithmetic on at all.
Steve Summit
(e-mail address removed)