views:

102

answers:

5

I have allocated a chunk of memory of type char and size is say 10 MB (i.e mem_size = 10 ):

int mem_size = 10; 
char *start_ptr;
if((start_ptr= malloc(mem_size*1024*1024*sizeof(char)))==NULL) {return -1;}

Now I want to store the size information in the header of the memory chunk.To make myself more clear, let's say: start_ptr = 0xaf868004 (This is the value I got from my execution, it changes every time).

Now I want to put the size information in the start of this pointer, i.e *start_ptr = mem_size*1024*1024;.

But I am not able to put this information in the start_ptr. I think the reason is because my ptr is of type char which only takes one byte but I am trying to store int which takes 4 bytes, is the problem .

I am not sure how to fix this problem..

+1  A: 
*((int*)start_ptr) = mem_size*1024*1024
compie
+5  A: 

You'll need to cast your char pointer to an int pointer. In two steps:

int *start_ptr_int = (int*)start_ptr;
*start_ptr_int = mem_size * 1024 * 1024;

In one step:

*((int*)start_ptr) = mem_size * 1024 * 1024;

The (int*) in front of your pointer name tells the compiler: "Yeah, I know this is not actually a pointer to int, but just pretend for the time being, okay?"

Thomas
Thanks Thomas for the answer.It makes sense..but a quick question for you. How do I print the value at that address. If I do printf("%d ",*start_ptr);It is still giving me 0 at that address..Am I making some mistake..
Adi
@Adi: you need to cast back to int in the printf too, eg. printf("%d", * ((int *)start_ptr))
Mike Dinsdale
Thanks Mike..I got it..
Adi
+1  A: 

You could also just memcpy the value in ...

ie

int toCopy = mem_size * 1024 * 1024;
memcpy( start_ptr, &toCopy, 4 );

You'd even be surprised how most compilers won't even make the memcpy call and will just set the value.

Goz
In this case, how do I print the value which I stored ..I am trying this method, but It is giving 0 at start_addr ..I want to make sure that ,the value is actually stored at that location.
Adi
+1  A: 

One way to do it without casts:

#include <stdlib.h>
struct Block {
    size_t size;
    char data[];
};
#define SIZE (1024*1024)
int main()
{
    struct Block* block = malloc(sizeof(struct Block) + SIZE);
    block->size = SIZE;
    char* start_ptr = block->data;
    // ...
}

Or, to get the effect you want, change one line:

char* start_ptr = (char*)block;
Richard Pennington
A: 

A comment on style: Don't do this:

if ((ptr=malloc()) == NULL)

There is nothing wrong with

ptr = malloc();
if (ptr == NULL) ...

Good programmers know what they could do with the language. Excellent programmers know why they shouldn't do it. ;)

And -1 to all posters who assume an int in C to always be 32 bits, including the OP in the thread title. An int is guaranteed to have at least 16 bits, and on 32 bit machines it is usually a safe assumption to have 32 bits, but your code may fail as soon as you move to a 64 bit machine.

Secure