开发者

How to store an integer value of 4 bytes in a memory of chunk which is malloced as type char

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

int mem_s开发者_开发知识库ize = 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..


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?"


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


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.


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;


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜