C question (memory allocation and access)

Ben Alexander bjal_cif at uhura.cc.rochester.edu
Wed Nov 15 18:52:15 AEST 1989


Followups have been redirected to comp.lang.c

In article <5322 at wpi.wpi.edu> mhampson at wpi.wpi.edu (Mark A. Hampson) writes:
>I have a question that I have not been able to find an answer that I feel 
>comfortable with regarding the following situation:
>
>I am attempting to allocate a block of memory as follows:
>
>int   m = 10;
>int   n = 10;
>void *block;
>int   block_siz;
>
>block_siz = 2*sizeof(int) + m*n*sizeof(double);
>block = malloc(block_siz);
>
>simple enough...
>
>I now wish to put two integers at the begining of this block of memory:
>
>block = m;
>(block+sizeof(int)) = n;   <---  here is where I am running into probs.

Actually, the line before this is the one that *should* be giving you
problems.  When you say "block = m;" you are telling the complier to make
block point to the address 10.  This means the the space allocated by
malloc is no longer accesible and that you will be accessing (probably)
sensitive areas of memory.  Bad Juju.  I would think that the complier
would give you a warning to the effect of "Non-portable pointer
assignment".

>My intention is to store m in the first int sized space in block and to 
>store n in the int sized space after it.
>
>The compiler that I am using tells me that it does not know the size of 
>block and therefore cannot perform the operation block+sizeof(int).  This
>makes some sence as block is of type void *.  That being the case, how can 
>I perform the operation that I want to?

To do what you want to do you should use the following code:
*((int *) block) = m;
*((int *) block + 1) = n;

The first line assigns the correct value to the first int-sized chunk of
block.  The (int *) typecast gives the complier the size of what block
points to, so it can do the assignment.

In the next line, the addition actually increments block to the next int
as opposed to adding 1 byte to block (that's what the typecast is for).
The indirection of the whole left-hand expression tells the compiler to
store n in the address of block started one int later.

>Thanks in advance:
>Mark A. Hampson

No problem.

Ben Alexander

P.S. I don't read comp.lang.c, so if you want to comment on this, please
e-mail me a copy of your post. 



More information about the Comp.lang.c mailing list